SMART on FHIR v2.2

Connect Health Apps to .care

Patients launch trusted third-party health apps directly from their .care portal. Clinicians open patient-context views from notes. Full OAuth2 + SMART on FHIR v2.2 with granular scope management.

Architecture

How SMART Launch Works

Three launch types, one secure OAuth2 flow. Patients, clinicians, and carers each get context-aware access.

Patient

Standalone Patient Launch

Patient is on .care dashboard and clicks "Connect Apple Health." App launches with their patient ID as context.

Clinician

EHR Launch (Clinician)

Clinician is viewing a note and clicks "Open in .care." Portal opens with patient + encounter context pre-loaded.

Family

Carer / Family Launch

Family member with delegated consent accesses patient-linked tools. Relationship token passed as context.

Complete Launch Sequence

1

App Registration

SMART app registered at chartscribe.care with client_id, redirect_uri, and scopes

Admin
2

Launch Request

Patient clicks "Launch My Health Apps" — .care builds launch URL with iss, launch context, and scopes

Patient / Clinician
3

OAuth2 Authorize

Redirected to auth server. Patient authenticates and approves scope consent

Auth Server
4

Token Exchange

Auth server returns authorization code. .care exchanges for access_token + patient context

Backend
5

FHIR Data Access

SMART app uses access_token to read patient data from ChartScribe FHIR server

SMART App
6

Contextual View

Patient sees their health data rendered in the connected SMART app, within .care iframe or redirect

Patient
Scope Reference

Launch Types & OAuth2 Scopes

Each launch type carries different scopes and context. Granular permission control for every scenario.

Implementation

Python FastAPI + OAuth2

Complete implementation with CSRF protection, consent validation, scope management, and audit logging.

python
from fastapi import APIRouter, Request, HTTPException
from authlib.integrations.starlette_client import OAuth
from urllib.parse import urlencode

router = APIRouter(prefix="/.care")

oauth = OAuth()
# Register your SMART client (do this at startup)
oauth.register(
    name="smart",
    client_id="chartscribe-care-client",
    client_secret="YOUR_CLIENT_SECRET",
    server_metadata_url="https://your-auth-server/.well-known/openid-configuration",
    client_kwargs={"scope": "patient/*.read launch/patient openid profile"},
)

@router.get("/launch")
async def smart_launch(
    request: Request,
    patient_id: str,
    launch_type: str = "patient",      # patient | clinician | carer
    app_id: str = None,                # optional: specific app to launch
):
    """Generate a SMART on FHIR launch URL for .care patient access."""
    
    # 1. Verify patient exists and has consented to data sharing
    patient = await get_patient_from_db(patient_id)
    if not patient:
        raise HTTPException(status_code=404, detail="Patient not found")
    if not patient.smart_consent_granted:
        raise HTTPException(status_code=403, detail="Patient has not consented to SMART app launch")
    
    # 2. Build scope set based on launch type
    scope_map = {
        "patient": "patient/*.read launch/patient openid profile",
        "clinician": "fhirUser patient/*.read launch/encounter openid profile",
        "carer": "patient/*.read user/*.read openid profile consent_extension",
    }
    scopes = scope_map.get(launch_type, scope_map["patient"])
    
    # 3. Build launch context
    launch_context = {
        "patient": patient_id,
        "encounter": request.query_params.get("encounter_id"),
        "launchType": launch_type,
    }
    
    # 4. Generate launch URL
    launch_params = {
        "iss": "https://chartscribe.care/fhir",          # Your FHIR server
        "launch": encode_launch_context(launch_context),  # Base64-encoded context
        "client_id": "chartscribe-care-client",
        "scope": scopes,
        "redirect_uri": "https://chartscribe.care/.care/callback",
        "response_type": "code",
        "state": generate_csrf_token(),                    # CSRF protection
        "aud": "https://chartscribe.care/fhir",           # Audience
    }
    
    authorize_url = f"https://your-auth-server/authorize?{urlencode(launch_params)}"
    
    # 5. Log the launch attempt for audit
    await audit_log(
        event="smart_launch_initiated",
        patient_id=patient_id,
        launch_type=launch_type,
        scopes=scopes,
    )
    
    return {
        "launch_url": authorize_url,
        "launch_type": launch_type,
        "scopes": scopes.split(),
        "patient_id": patient_id,
    }


def encode_launch_context(ctx: dict) -> str:
    """Base64-encode the launch context for SMART EHR launch."""
    import base64, json
    return base64.urlsafe_b64encode(json.dumps(ctx).encode()).decode().rstrip("=")


def generate_csrf_token() -> str:
    """Generate a cryptographically secure CSRF state token."""
    import secrets
    return secrets.token_urlsafe(32)

CSRF state tokens

Consent validation

3 launch types

FHIR v2.2 server

API Reference

Endpoints to Implement

Three core endpoints covering the full SMART launch lifecycle.

GET/.care/launch

Generate a SMART launch URL for the patient. Returns the full authorization URL with context parameters.

Query: patient_id (required), launch_type (patient|clinician|carer)

{ "launch_url": "https://auth-server/authorize?iss=...&launch=...&scope=..." }
POST/.care/callback

Handle OAuth2 callback from the authorization server. Exchange code for token, validate patient context, establish .care session.

Query: Body: { code, state, iss }

{ "access_token": "eyJ...", "patient": "pat-123", "context": { ... } }
GET/.care/patient/{patient_id}/apps

List available SMART apps for a given patient, filtered by their consent preferences and connected integrations.

Query: —

{ "apps": [{ "name": "Apple Health", "launch_url": "...", "icon": "..." }] }
UI / UX

Launch Buttons & Patient Flow

Where patients and clinicians trigger SMART launches within ChartScribe.

Patient Dashboard (.care)

Clinician View (Doctor Portal)

Patient Consent Required

Every SMART launch requires explicit patient consent. The consent is recorded at registration, verified before each launch, and can be revoked at any time from the .care privacy settings. All launches are logged for GDPR Article 9 audit compliance.

Testing

Testing & Validation Checklist

Before going live, every launch flow must pass these four gates.

Gate 1

Public SMART Sandboxes

Test against Epic Sandbox (open.epic.com), Cerner Code, and NHS England sandboxes. Verify launch URL generation and token exchange.

Gate 2

Token Flow Validation

Verify complete OAuth2 flow: authorize → code → token → patient context. Test token refresh and expiry handling.

Gate 3

Patient Context Pass-Through

Ensure patient ID and encounter context are correctly passed and decoded. Verify no context leakage between patients.

Gate 4

Security & Consent Audit

Validate CSRF tokens, consent checks, scope enforcement, and audit logging. Confirm GDPR Article 9 compliance for health data.

Public Test Environments

Epic Sandbox

https://open.epic.com

SMART launch + FHIR R4 testing

Cerner Code

https://code.cerner.com

OAuth2 + patient context flows

NHS England

https://digital.nhs.uk

UK-specific SMART conformance

Ready to connect health apps?

Our team will register your SMART apps, configure OAuth2 scopes, and validate the launch flow within 48 hours.

We use cookies to improve your experience

Necessary cookies are always active. Analytics and marketing cookies help us improve ChartScribe and show relevant content. You can manage your preferences at any time.

We use cookies to improve your experience

Necessary cookies are always active. Analytics and marketing cookies help us improve ChartScribe and show relevant content. You can manage your preferences at any time.