Aidbox User Docs
Run Aidbox locallyRun Aidbox in SandboxTalk to us Ask community
  • Aidbox FHIR platform documentation
    • Features
    • Architecture
  • Getting Started
    • Run Aidbox in Sandbox
    • Run Aidbox locally
    • Run Aidbox on AWS
    • Upload Sample Data
  • Tutorials
    • CRUD, Search Tutorials
      • Delete data
      • Set up uniqueness in Resource
      • Search Tutorials
        • Custom SearchParameter tutorial
        • Create custom Aidbox Search resource
        • Multilingual search tutorial
        • Migrate from Aidbox SearchParameter to FHIR SearchParameter
        • Change sort order by locale collation
    • Bulk API Tutorials
      • 🎓Synthea by Bulk API
      • 🎓$dump-sql tutorial
    • Security & Access Control Tutorials
      • Allow patients to see their own data
      • Restrict operations on resource type
      • Relationship-based access control
      • Creating user & set up full user access
      • Restricting Access to Patient Data
      • Create and test access control
      • RBAC
        • Flexible RBAC built-in to Aidbox
        • RBAC with JWT containing role
        • RBAC with ACL
      • Set-up token introspection
      • Prohibit user to login
      • Managing Admin Access to the Aidbox UI Using Okta Groups
      • Run Multibox locally
      • How to enable labels-based access control
      • How to enable patient data access API
      • How to enable SMART on FHIR on Patient Access API
      • How to enable hierarchical access control
      • How to configure Audit Log
      • How is an HTTP request processed in Aidbox
      • How to configure SSO with another Aidbox instance to access Aidbox UI
      • How to configure SSO with Okta to access Aidbox UI
      • How to configure sign-in with Apple for access to the Aidbox UI
      • How to configure Azure AD SSO for access to the Aidbox UI
      • How to configure Microsoft AD FS for access to the Aidbox UI
      • How to configure Azure AD SSO with certificate authentication for access to the Aidbox UI
      • How to configure GitHub SSO for access to Aidbox UI
      • How to configure Keycloak for access for AidboxUI
      • How to implement Consent-based Access Control using FHIR Search and Aidbox Access Policy
      • Debug Access Control
      • AccessPolicy best practices
    • Terminology Tutorials
      • Load ICD-10 terminology into Aidbox
      • Uploading IG terminology content to external FHIR terminology server
    • Validation Tutorials
      • Upload FHIR Implementation Guide
        • Environment Variable
        • Aidbox UI
          • IG Package from Aidbox Registry
          • Public URL to IG Package
          • Local IG Package
        • Aidbox FHIR API
        • UploadFIG Tool
      • ISiK
      • Carin BB
      • US Core
      • Davinci Pdex
      • mCode
    • Integration Toolkit Tutorials
      • Postmark integration tutorial
      • Mailgun integration tutorial
    • Subscriptions Tutorials
      • AidboxTopicSubscription NATS tutorial
    • Other tutorials
      • Run Aidbox with FHIR R6
      • Migrate from Multibox to Aidbox
      • SDC with Custom Resources
      • How to create FHIR NPM package
      • Migrate from legacy licence portal to Aidbox portal
      • How to run Aidbox in GCP Cloud Run
  • Overview
    • Licensing and Support
    • Aidbox user portal
      • Projects
      • Licenses
      • Members
    • Aidbox UI
      • Aidbox Notebooks
      • REST Console
      • Database Console
      • Attrs stats
      • DB Tables
      • DB Queries
    • Versioning
    • Release Notes
    • Contact us
  • Configuration
    • Settings
    • Configure Aidbox and Multibox
    • Init Bundle
  • API
    • REST API
      • CRUD
        • Create
        • Read
        • Update
        • Patch
        • Delete
      • FHIR Search
        • SearchParameter
        • Include and Revinclude
        • Chaining
      • Aidbox Search
      • Bundle
      • History
      • $everything on Patient
      • Other
        • Aidbox & FHIR formats
        • Capability Statement
        • $document
        • Observation/$lastn
        • $validate
        • SQL endpoints
        • $matcho
        • $to-format
        • Aidbox version
        • Health check
    • Bulk API
      • Configure Access Policies for Bulk API
      • $dump
      • $dump-sql
      • $dump-csv
      • $export
      • $load & /fhir/$load
      • $import & /fhir/$import
      • aidbox.bulk data import
      • Bulk import from an S3 bucket
    • Batch/Transaction
    • GraphQL API
    • Other APIs
      • Plan API
        • Provider Directory API
          • Practitioner
          • PractitionerRole
          • Organization
          • OrganizationAffiliation
        • Plan API Overview
      • Archive/Restore API
        • create-archive
        • restore-archive
        • prune-archived-data
        • delete-archive
      • ETAG support
      • Cache
      • Changes API
      • RPC API
      • Sequence API
      • Encryption API
      • Batch Upsert
  • Modules
    • Profiling and validation
      • FHIR Schema Validator
        • Aidbox FHIR IGs Registry
        • Setup Aidbox with FHIR Schema validation engine
      • Skip validation of references in resource using request header
      • Asynchronous resource validation
    • Access Control
      • Identity Management
        • User Management
        • Application/Client Management
      • Authentication
        • Basic HTTP Authentication
        • OAuth 2.0
        • Token Introspector
        • SSO with External Identity Provider
      • Authorization
        • Access Policies
        • SMART on FHIR
          • SMART Client Authorization
            • SMART App Launch
            • SMART Backend services
          • SMART Client Authentication
            • SMART: Asymmetric (/"private key JWT") authentication
            • SMART: Symmetric (/"client secret") authentication
          • SMART: Scopes for Limiting Access
          • Pass Inferno tests with Aidbox
          • Example: SMART App Launch using Aidbox and Keycloak
          • Example: SMART App Launch using Smartbox and Keycloak
        • Scoped API
          • Organization-based hierarchical access control
          • Compartments API
          • Patient data access API
        • Label-based Access Control
      • Audit & Logging
    • Observability
      • Getting started
        • Run Aidbox with OpenTelemetry locally
        • How to export telemetry to the OTEL collector
      • Logs
        • How-to guides
          • OpenTelemetry logs
          • Elastic Logs and Monitoring Integration
          • Datadog Log management integration
          • Loki Log management integration
        • Tutorials
          • Log analysis and visualization tutorial
          • Export logs to Datadog tutorial
        • Extending Aidbox Logs
        • Technical reference
          • Log appenders
          • Log transformations
          • Log Schema
          • OTEL logs exporter parameters
      • Metrics
        • How-to guides
          • How to export metrics to the OTEL collector
          • Use Aidbox Metrics Server
          • Set-up Grafana integration
        • Technical reference
          • OpenTelemetry Metrics
          • OTEL metrics exporter parameters
      • Traces
        • How to use tracing
        • OTEL traces exporter parameters
    • Subscriptions
      • Aidbox topic-based subscriptions
        • Kafka AidboxTopicDestination
        • Webhook AidboxTopicDestination
        • GCP Pub/Sub AidboxTopicDestination
        • Tutorial: produce QuestionnaireResponse to Kafka topic
      • Aidbox SubSubscriptions
    • Aidbox Forms
      • Getting started
      • Aidbox Forms Interface
      • Aidbox UI Builder
        • UI Builder Interface
        • Form creation
          • Form Settings
          • Widgets
          • Components
          • Versioning
          • Form customisation in Theme Editor
          • Form signature
          • How-to guides
            • How to: populate forms with data
            • How to extract data from forms
            • How to calculate form filling percentage
          • Multilingual forms
          • FHIRPath Editor
        • Import Questionnaire
        • Form sharing
        • Printing forms
          • Template-based PDF generation
        • FHIR versions
        • Offline forms
        • Embedding
          • Request Interception
        • Configuration
        • Forms multitenancy
        • Building reports using SQL on FHIR
        • Integration with external terminology servers
        • External FHIR servers as a data backend
        • Store attachments in S3-like storages
      • Access Control in Forms
      • Audit Logging in Forms
      • Aidbox Form Gallery
    • Define extensions
      • Extensions using StructureDefinition
      • Extensions using FHIRSchema
    • Custom Resources
      • Custom resources using FHIR Schema
      • Custom resources using StructureDefinition
      • Migrate to FHIR Schema
        • Migrate custom resources defined with Entity & Attributes to FHIR Schema
        • Migrate custom resources defined with Zen to FHIR Schema
    • Aidbox terminology module
      • Concept
        • $translate-concepts
        • Handling hierarchies using ancestors
      • ValueSet
        • ValueSet Expansion
        • ValueSet Code Validation
        • Create a ValueSet
      • CodeSystem
        • CodeSystem Concept Lookup
        • CodeSystem Subsumption testing
        • CodeSystem Code Composition
      • Import external terminologies
        • Import flat file (/CSV)
        • $import operation
        • Ready-to-use terminologies
      • $translate on ConceptMap
    • SQL on FHIR
      • Defining flat views with View Definitions
      • Query data from flat views
      • Reference
    • Integration toolkit
      • C-CDA / FHIR Converter
        • List of supported templates
          • Admission Diagnosis Section (/V3)
          • Advance Directives Section (/entries optional) (/V3)
          • Advance Directives Section (/entries required) (/V3)
          • Allergies and Intolerances Section (/entries optional) (/V3)
          • Allergies and Intolerances Section (/entries required) (/V3)
          • Assessment Section
          • Chief Complaint Section
          • Chief Complaint and Reason for Visit Section
          • Complications Section (/V3)
          • Course of Care Section
          • DICOM Object Catalog Section - DCM 121181
          • Default Section Rules
          • Discharge Diagnosis Section (/V3)
          • Document Header
          • Encounters Section (/entries optional) (/V3)
          • Encounters Section (/entries required) (/V3)
          • Family History Section (/V3)
          • Functional Status Section (/V2)
          • General Status Section
          • Goals Section
          • Health Concerns Section (/V2)
          • History of Present Illness Section
          • Hospital Consultations Section
          • Hospital Course Section
          • Hospital Discharge Instructions Section
          • Hospital Discharge Physical Section
          • Hospital Discharge Studies Summary Section
          • Immunizations Section (/entries optional) (/V3)
          • Immunizations Section (/entries required) (/V3)
          • Medical (/General) History Section
          • Medical Equipment Section (/V2)
          • Medications Administered Section (/V2)
          • Medications Section (/entries optional) (/V2)
          • Medications Section (/entries required) (/V2)
          • Mental Status Section (/V2)
          • Notes
          • Nutrition Section
          • Objective Section
          • Operative Note Fluids Section
          • Operative Note Surgical Procedure Section
          • Past Medical History (/V3)
          • Payers Section (/V3)
          • Plan of Treatment Section (/V2)
          • Postprocedure Diagnosis Section (/V3)
          • Preoperative Diagnosis Section (/V3)
          • Problem Section (/entries optional) (/V3)
          • Problem Section (/entries required) (/V3)
          • Procedure Description Section
          • Procedure Disposition Section
          • Procedure Estimated Blood Loss Section
          • Procedure Implants Section
          • Procedure Specimens Taken Section
          • Procedures Section (/entries optional) (/V2)
          • Procedures Section (/entries required) (/V2)
          • Reason for Visit Section
          • Results Section (/entries optional) (/V3)
          • Results Section (/entries required) (/V3)
          • Review of Systems Section
          • Social History Section (/V3)
          • Vital Signs Section (/entries optional) (/V3)
          • Vital Signs Section (/entries required) (/V3)
        • How to deploy the service
        • Producing C-CDA documents
        • How to customize conversion rules
      • HL7 v2 Integration
        • HL7 v2 integration with Aidbox Project
        • Mappings with lisp/mapping
      • X12 message converter
      • Analytics
        • Power BI
      • Mappings
      • Email Providers integration
        • Setup SMTP provider
    • SMARTbox | FHIR API for EHRs
      • Get started
        • Set up Smartbox locally
        • Deploy Smartbox with Kubernetes
      • (/g)(/10) Standardized API for patient and population services
      • The B11 Decision Support Interventions
        • Source attributes
        • Feedback Sections
      • How-to guides
        • Pass Inferno tests with Smartbox
        • Perform EHR launch
        • Pass Inferno Visual Inspection and Attestation
        • Revoke granted access
        • Set up EHR-level customization
        • Check email templates
        • Setup email provider
        • Register users
        • Set up SSO with Auth0
        • Publish Terms of Use link onto the documentation page
        • Find out what resources were exported during the $export operation
        • Find documentation endpoint
      • Background information
        • Considerations for Testing with Inferno ONC
        • Adding Clients for Inferno tests
        • Multitenancy approach
        • What is Tenant
        • Email templating
    • ePrescription
      • Getting started
      • Authentication with mTLS
      • Pharmacies synchronization
      • Prescribing
        • NewRx Message
        • CancelRx Message
        • How to test Callback
      • Directory
        • DirectoryDownload Message
        • GetProviderLocation Message
        • AddProviderLocation Message
        • UpdateProviderLocation Message
        • DisableProviderLocation Message
      • Medications
        • FDB
      • References
        • Environment Variables
      • Frequently Asked Questions
    • Other modules
      • MDM
        • Train model
        • Configure MDM module
        • Find duplicates: $match
        • Mathematical details
      • MCP
  • Database
    • Overview
    • Database schema
    • PostgreSQL Extensions
    • AidboxDB
      • HA AidboxDB
    • Tutorials
      • Migrate to AidboxDB 16
      • Working with pgAgent
  • File storage
    • AWS S3
    • GCP Cloud Storage
    • Azure Blob Storage
    • Oracle Cloud Storage
  • Deployment and maintenance
    • Deploy Aidbox
      • Run Aidbox on Kubernetes
        • Deploy Production-ready Aidbox to Kubernetes
        • Deploy Aidbox with Helm Charts
        • Highly Available Aidbox
        • Self-signed SSL certificates
      • Run Aidbox on managed PostgreSQL
      • How to inject env variables into Init Bundle
    • Backup and Restore
      • Crunchy Operator (/pgBackRest)
      • pg_dump
      • pg_basebackup
      • WAL-G
    • Indexes
      • Get suggested indexes
      • Create indexes manually
  • App development
    • Use Aidbox with React
    • Aidbox SDK
      • Aidbox JavaScript SDK
      • Apps
      • NodeJs SDK
      • Python SDK
    • Examples
  • Reference
    • Matcho DSL reference
    • FHIR Schema reference
    • Settings reference
      • General
      • FHIR
      • Security & Access Control
      • Modules
      • Database
      • Web Server
      • Observability
      • Zen Project
    • Environment variables
      • Aidbox required environment variables
      • Optional environment variables
      • AidboxDB environment variables
    • System resources reference
      • IAM Module Resources
      • SDC Module Resources
      • Base Module Resources
      • Bulk Module Resources
      • AWF Module Resources
      • Cloud Module Resources
      • HL7v2 Module Resources
      • SQL on FHIR Module Resources
    • Email Providers reference
      • Notification resource reference
      • Mailgun environment variables
      • Postmark environment variables
    • Aidbox Forms reference
      • FHIR SDC API
      • Aidbox SDC API
      • Generating Questionnaire from PDF API
    • Aidbox SQL functions
  • Deprecated
    • Deprecated
      • Zen-related
        • RPC reference
          • aidbox
            • mdm
              • aidbox.mdm/update-mdm-tables
              • aidbox.mdm/match
        • FTR
        • Aidbox configuration project
          • Run Aidbox locally using Aidbox Configuraiton project
          • Aidbox configuration project structure
          • Set up and use configuration projects
          • Enable IGs
          • Repository
          • Seed Import
          • Manage Indexes in Zen Project
          • Seed v2
          • 🎓Migrate to git Aidbox Configuration Projects
          • Aidbox Configuration project reference
            • Zen Configuration
            • Aidbox project RPC reference
            • aidbox.config/config
          • Custom resources using Aidbox Project
          • First-Class Extensions using Zen
          • Zen Indexes
        • US Core IG
          • US Core IG support reference
        • Workflow Engine
          • Task
            • Aidbox Built-in Tasks
            • Task Executor API
            • Task User API
          • Workflow
            • Workflow User API
          • Services
          • Monitoring
        • FHIR conformance Deprecated guides
          • Touchstone FHIR 4.0.1 basic server
          • Touchstone FHIR USCore ClinData
          • How to enable US Core IG
            • Start Aidbox locally with US Core IG enabled
            • Add US Core IG to a running Aidbox instance
          • HL7 FHIR Da Vinci PDex Plan Net IG
        • Terminology Deprecated Tutorials
          • Inferno Test-Suite US Core 3.1.1
        • API constructor (/beta)
        • zen-lang validator
          • Write a custom zen profile
          • Load zen profiles into Aidbox
        • FHIR topic-based subscriptions
          • Set up SubscriptionTopic
          • Tutorial: Subscribe to Topic (/R4B)
          • API Reference
            • Subscription API
        • 🏗️FHIR Terminology Repository
          • FTR Specification
          • Create an FTR instance
            • FTR from CSV
            • FTR from FHIR IG
            • FTR from FTR — Direct Dependency
            • FTR from FTR — Supplement
          • FTR Manifest
          • Load SNOMED CT into Aidbox
          • Load LOINC into Aidbox
          • Load ICD-10-CM into Aidbox
          • Load RxNorm into Aidbox
          • Load US VSAC Package to Aidbox
          • Import via FTR
        • Zen Search Parameters
      • Entity / Attribute
        • Entities & Attributes
        • First-Class Extensions using Attribute
        • Custom Resources using Entity
        • Working with Extensions
        • Aidbox Search Parameters
      • Forms
      • Other
        • Custom Search
        • SearchQuery
        • Subscribe to new Patient resource
        • App Development Deprecated Tutorials
          • Receive logs from your app
            • X-Audit header
          • Patient Encounter notification Application
        • Other Deprecated Tutorials
          • Resource generation with map-to-fhir-bundle-task and subscription triggers
          • APM Aidbox
          • Automatically archive AuditEvent resources in GCP storage guide
          • HL7 v2 pipeline with Patient mapping
          • How to migrate to Apline Linux
          • How to migrate transaction id to bigint
          • How to fix broken dates
          • Configure multi-tenancy
        • AidboxProfile
        • GCP Pub/Sub
Powered by GitBook
On this page
  • About this tutorial
  • Prerequisites
  • Structure of imported resources
  • User Login‌
  • Patient Resource access
  • Encounter access
  • Observation access
  • Read access
  • Write access
  • Access to the next of kin records

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. Security & Access Control Tutorials

Allow patients to see their own data

This guide shows how to set-up access control to make patients be able to see their own data

About this tutorial

In this tutorial, you will learn how to manage user access to patient resources.

Prerequisites

Once you access the Aidbox REST Console, load resources that you need to work with policies:

POST /$import

id: patient_import
inputFormat: application/fhir+ndjson
contentEncoding: gzip
mode: bulk
inputs:
- resourceType: Client
  url: https://storage.googleapis.com/aidbox-public/demo/client.ndjson.gz
- resourceType: User
  url: https://storage.googleapis.com/aidbox-public/demo/user.ndjson.gz
- resourceType: Patient
  url: https://storage.googleapis.com/aidbox-public/demo/patient.ndjson.gz
- resourceType: Encounter
  url: https://storage.googleapis.com/aidbox-public/demo/encounter.ndjson.gz
- resourceType: Observation
  url: https://storage.googleapis.com/aidbox-public/demo/observation.ndjson.gz
- resourceType: Practitioner
  url: https://storage.googleapis.com/aidbox-public/demo/practitioner.ndjson.gz

Structure of imported resources

In the previous step, we have imported a client that will authenticate users and two users with corresponding sets of related resources shown on the picture below. Overlapping outlines indicates the relation between enclosed resources. A similar diagram applies to User-2.

User Login‌

Now you can use Postman to log in as a user. In this example, we log in as User-1.

POST /auth/token

{
  "client_id": "myapp"
  "client_secret": "verysecret"
  "username": "patient-user"
  "password": "admin" 
  "grant_type": "password"
}
{
  "token_type": "Bearer",
  "userinfo": {
    "data": {
      "roles": ["Patient"],
      "patient_id": "new-patient"
    },
    "resourceType": "User",
    "id": "patient-user",
    "meta": {
      "lastUpdated": "2020-11-06T12:18:19.530001Z",
      "createdAt": "2020-11-03T14:09:03.010136Z",
      "versionId": "426"
    }
  },
  "access_token": "MjYzOTkyZDEtODg4ZC00NTBlLTgxNDEtNjIzM2Y4NWQ1M2Vk"
}

Notice the patient_id field of userinfo . This is the id of the Patient resource associated with our user. It will be used further in Access Policies to decide if access should be granted or not. In general, you need to specify data.patient_id: some_patient_id in your User resource to establish a relation to a Patient resource.‌

At this point there are no access policies that allow the user to access any resources. So all attempts to make requests for Resources will be denied.

Patient Resource access

Let's add our first policy that will grant us access to the Patient resource associated with our user.

POST /AccessPolicy

id: patient-access
engine: matcho
matcho:
  uri: '#/Patient/.*'
  params:
    resource/id: .user.data.patient_id  
  request-method: get
engine: matcho
matcho:
  uri: '#/Patient/.*'
  params: 
    resource/id: .user.data.patient_id
  request-method: get
id: patient-access
resourceType: AccessPolicy
meta: 
  lastUpdated: '2020-11-10T15:00:59.497835Z'
  createdAt: '2020-11-10T15:00:59.497835Z'
  versionId: '110'

Here we specified that Access Policy would grant GET access to a URI that matches #/Patient/.* regex if the request parameter named resource/id matches data.patient value of the user that makes the request.‌

So now we can read our patient. The part of the URL after /Patient/, namely new-patient, is parsed by Access Policy engine as the resource/id parameter of the request:

GET /Patient/new-patient
{
    "name": [
        {
            "given": ["Luke"]
        },
        {
            "family": "Skywalker"
        }
    ],
    "gender": "male",
    "birthDate": "2145-08-12",
    "id": "new-patient",
    "resourceType": "Patient",
    "meta": {
        "lastUpdated": "2020-11-10T13:51:16.780576Z",
        "createdAt": "2020-11-10T11:38:52.402256Z",
        "versionId": "83"
    }
}

You can check that access to any other existing Patient resource, for instance, that one with id new-patient1, will be denied.

Encounter access

Now let's give our user the ability to retrieve all encounters where they are referred to as a subject:

POST /AccessPolicy

id: search-patient-encounter
engine: matcho
matcho:
  uri: /Encounter
  params:
    patient: .user.data.patient_id
  request-method: get
engine: matcho
matcho:
  uri: /Encounter
  params:
    patient: .user.data.patient_id
resourceType: AccessPolicy
id: search-patient-encounter
meta:
  lastUpdated: '2020-11-05T15:28:58.054136Z'
  createdAt: '2020-11-05T15:28:58.054136Z'
  versionId: '0'

Finally, we can make a request for the list of patient encounters.

GET /Encounter?patient=new-patient
{
  "query-time": 7,
  "meta": {
    "versionId": "155"
  },
  "type": "searchset",
  "resourceType": "Bundle",
  "total": 1,
  "link": [
    {
      "relation": "first",
      "url": "/Encounter?patient=new-patient&page=1"
    },
    {
      "relation": "self",
      "url": "/Encounter?patient=new-patient&page=1"
    }
  ],
  "query-timeout": 60000,
  "entry": [
    {
      "resource": {
         "class": {
            "code": "AMB"
          },
         "status": "planned",
         "subject": {
            "id": "new-patient",
            "resourceType": "Patient"
          },
         "participant": [
           {
             "individual": {
               "id": "practitioner-1",
               "resourceType": "Practitioner"
             }
           }
         ],
         "id": "enc1",
               "resourceType": "Encounter",
               "meta": {
                    "lastUpdated": "2020-11-10T11:11:39.464261Z",
                    "createdAt": "2020-11-06T19:14:46.247628Z",
                    "versionId": "150"
               }
      },
      "fullUrl": "/Encounter/enc1",
      "link": [
        {
          "relation": "self",
          "url": "/Encounter/enc1"
        }
      ]
    }
  ],
  "query-sql": [
    "SELECT \"encounter\".* FROM \"encounter\" WHERE \"encounter\".resource @> ? LIMIT ? OFFSET ? ",
    "{\"subject\":{\"id\":\"new-patient\",\"resourceType\":\"Patient\"}}",
    100,
    0
  ]
}

Observation access

Read access

Granting access to observations is similar to the previous case. We just add another policy that looks just like the previous one, but matches against another URI. It is so similar that we should stop there and think a little about what happens if we want to grant read access to more resources — we will end up with a bunch of almost indistinguishable policies. A better approach, in this case, is to use the CompartmentDefinition resource.

POST /fhir/CompartmentDefinition

id: patient
url: http://hl7.org/fhir/CompartmentDefinition/patient
code: Patient
search: true
status: draft
resource:
  - code: Encounter
    param: 
      - patient
  - code: Observation
    param: 
      - subject
      - performer

And that's it! We don't even need to add more policies, since we already have the policy that allows the user to access URIs that match /Patient/.* regex.

GET /Patient/new-patient/Observation
{
 "query-time": 7,
 "meta": {
  "versionId": "171"
 },
 "type": "searchset",
 "resourceType": "Bundle",
 "total": 2,
 "link": [
  {
   "relation": "first",
   "url": "/Observation?_filter=subject eq 'new-patient' or performer eq 'new-patient'&page=1"
  },
  {
   "relation": "self",
   "url": "/Observation?_filter=subject eq 'new-patient' or performer eq 'new-patient'&page=1"
  }
 ],
 "query-timeout": 60000,
 "entry": [
  {
   "resource": {
    "class": {
     "coding": [
      {
       "code": "11557-6"
      }
     ]
    },
    "status": "registered",
    "subject": {
     "id": "new-patient",
     "resourceType": "Patient"
    },
    "performer": [
     {
      "id": "practitioner-1",
      "resourceType": "Practitioner"
     }
    ],
    "resourceType": "Observation",
    "id": "observation-1",
    "meta": {
     "lastUpdated": "2020-11-06T19:14:46.078643Z",
     "createdAt": "2020-11-06T19:14:46.078643Z",
     "versionId": "0"
    }
   },
   "fullUrl": "/Observation/observation-1",
   "link": [
    {
     "relation": "self",
     "url": "/Observation/observation-1"
    }
   ]
  },
  {
   "resource": {
    "class": {
     "coding": [
      {
       "code": "11557-6"
      }
     ]
    },
    "status": "registered",
    "subject": {
     "id": "new-patient",
     "resourceType": "Patient"
    },
    "performer": [
     {
      "id": "new-patient",
      "resourceType": "Patient"
     }
    ],
    "resourceType": "Observation",
    "id": "observation-3",
    "meta": {
     "lastUpdated": "2020-11-06T19:14:46.078643Z",
     "createdAt": "2020-11-06T19:14:46.078643Z",
     "versionId": "0"
    }
   },
   "fullUrl": "/Observation/observation-3",
   "link": [
    {
     "relation": "self",
     "url": "/Observation/observation-3"
    }
   ]
  }
 ],
 "query-sql": [
  "SELECT \"observation\".* FROM \"observation\" WHERE (\"observation\".resource @> ? OR \"observation\".resource @> ?) LIMIT ? OFFSET ? ",
  "{\"subject\":{\"id\":\"new-patient\"}}",
  "{\"performer\":[{\"id\":\"new-patient\"}]}",
  100,
  0
 ]
}

Write access

The user should be able to create their own observation, e.g., to report blood sugar level. The following policy manages this case:

POST /AccessPolicy

id: create-patient-observation
engine: matcho
matcho:
  uri: '/Observation'
  body:
    subject:
      id: .user.data.patient_id
      resourceType: Patient
    performer:
      $contains:
        id: .user.data.patient_id
        resourceType: Patient
  request-method: post

With this policy, we can only create observations where the subject and performer must be the user's patient.

POST /Observation

{
  "id": "observation-3",
  "code": {
    "coding": [
      {
        "code": "11557-6"
      }
    ]
  },
  "status": "registered",
  "subject": {
    "id": "new-patient",
    "resourceType": "Patient"
  },
  "performer": [
    {
      "id": "new-patient",
      "resourceType": "Patient"
    }
  ]
}

Now it's time to make an important note. In general, it is not possible to use some kind of CompartmentDefinition approach to grant write access to many resources at once, as we did previously for read access. That's because resources may require sophisticated logic to define which part of a resource could have write access and which not. Such logic may even lie beyond the abilities of the Access Control mechanism and in this case custom API is the only resort. But in a quite simple scenario like the creation of observation, Access Policies are helpful.

Let's create a new policy that allows our user to update their observations through the PATCH method. Matcho engine is no longer enough to make a rule for this kind of request since it only relies on the request and the user parameters. Now we need to peek into the requested resource to understand if it is related to our user and could be patched.

POST /AccessPolicy

id: patch-observation
link:
  - id: Patch
    resourceType: Operation
engine: complex
and:
  - engine: sql
    sql:
      query: > 
        select true from observation 
        where resource#>>'{subject,id}' = {{user.data.patient_id}} 
        and id = {{params.resource/id}}
        and resource->'performer' @> jsonb_build_array(jsonb_build_object('resourceType', 'Patient', 'id', {{user.data.patient_id}}::text))
  - engine: json-schema
    schema:
      properties:
        body:
          properties:
            subject:
              optional: true
              properties:
                id:
                  constant:
                    $data: '#/user/data/patient_id’

Now we can try to update our patient and the patient related to the User-2 and observe the difference in the responses.

Access to the next of kin records

Access policies depend a lot on how we model our resources. FHIR doesn't provide convenient facilities to make relations between patients. The easiest way to add such relations is to enhance a User resource with the list of related patients. Let's define that Patient-2 is related to User-1.

PATCH /User/patient-user

data:
  related_patients:
    - new-patient1

To grant User-1 access to related patients, we should simply update patient-access policy.

PUT /AccessPolicy/patient-access

engine: matcho
matcho:
  uri: '#/Patient/.*'
  user:
    data:
      $one-of:
        - related_patients:
            $contains: .params.resource/id
        - patient_id: .params.resource/id
  request-method: get
PreviousSecurity & Access Control TutorialsNextRestrict operations on resource type

Last updated 8 days ago

Was this helpful?

The access-token field of user-info will be needed to perform requests on behalf of our User. See how to perform user request with a token.

And this policy is a bit tricky. The allowed URI is /Encounter and it doesn't contain any additional parts that could be identified as request parameters as in the previous case. So, in order to provide the required request parameter patient to the Access Policy matching engine, we have to specify it as the query parameter of our request. And after the Access Policy engine allows such a request, the Search Engine comes into play. It filters out encounters that do not match the condition of patient = our-patient-id. To know more about how the Aidbox Search works, see the . To know more about the available search parameters, refer to the section of the FHIR documentation for the resource of interest.

Now, when we've created a CompartmentDefinition resource, we can access patient-related resources with such requests: GET /Patient/{patient-id}/{resource}. To know in detail about how compartments work, see the .

If we want to grant access to some other resource, we just need to add it to the CompartmentDefinition resource that we've created earlier. See to know what resources can be added to a patient compartment. And we can get rid of the Access Policy that was previously created for encounters.

here
Search section
Search Parameters
Compartments tutorial
FHIR documentation