



image::https://specifications.openehr.org/images/openEHR_logo_RGB.svg["openEHR logo",align="center"]

# SMART on openEHR (SMART)





## Acknowledgements

### Primary Author

* Sidharth Ramesh; Medblocks.
* Sebastian Iancu; Architect, Code24, Netherlands

### Contributors

This specification has benefited from formal and informal input from the openEHR and wider health informatics community. The openEHR Foundation would like to recognise the following for their contributions.

* Ian McNicoll MD, FreshEHR, UK
* Bostjan Lah, Senior Architect, Better, Slovenia

A significant part of the design ideas of this specification was derived from:

* SMART App Launch - Release 2.1.0, published by HL7® FHIR® standard

### Trademarks

* 'openEHR' is a registered trademark of the openEHR Foundation
* HL7® and FHIR® are the registered trademark of the Health Level Seven International and their use does not constitute endorsement by HL7
* SMART™ and the SMART logos are trademarks of The Children’s Medical Center Corporation. Used with permission.


# Preface

## Purpose

This document describes the SMART framework for an openEHR enabled platform.

The intended audience includes:

* EHR systems, Platform or Application vendors;
* Standards bodies producing health informatics standards;
* Solution vendors.

## Related Documents

Prerequisite documents for reading this document include:

* The {openehr_overview}[openEHR Architecture Overview^]
* {openehr_its_rest_releases}[openEHR REST APIs]
* HL7 FHIR https://hl7.org/fhir/smart-app-launch/STU2.1/[SMART App Launch Implementation Guide^]
* 'About SMART' page on https://smarthealthit.org/about-smart-2/[SMART Health IT^]
* {ietf_html}/rfc6749[OAuth 2.0 Authorization Framework^]
* https://openid.net/specs/openid-connect-core-1_0.html#Authentication[OpenId Connect (OIDC)^]

## Status

This specification is in the DEVELOPMENT state. The development version of this document can be found at {openehr_smart_app_launch}[{openehr_smart_app_launch}^].

Known omissions or questions are indicated in the text with a 'to be determined' paragraph, as follows:
*TBD*: (example To Be Determined paragraph)

## Feedback

Feedback may be provided on the {openehr_technical_list}/its[openEHR ITS forum^].

Issues may be raised on the https://specifications.openehr.org/components/{component}/open_issues[specifications Problem Report tracker^].

To see changes made due to previously reported issues, see the https://specifications.openehr.org/components/{component}/history[{component} component Change Request tracker^].


# Overview

## Background

*SMART* stands for “Substitutable Medical Applications and Reusable Technologies”, a healthcare standard enabling applications to access clinical information from a data store.
It was originally proposed by the https://smarthealthit.org/[SMART Health IT^] project (run by the Computational Health Informatics Program at Boston Children’s Hospital) and later formalized as https://hl7.org/fhir/smart-app-launch/STU2.1/[SMART App Launch Framework^], layered on top of the {hl7_fhir}[FHIR APIs^] to facilitate standardized data access.

The specification builds on {ietf_html}/rfc6749[OAuth 2.0^] and https://openid.net/specs/openid-connect-core-1_0.html#Authentication[OpenID Connect (OIDC)^], widely adopted industry standards for authentication and authorization.
It allows third-party applications to authenticate and interoperate securely with any compliant system.
It also defines launch sequences, token scopes, context passing mechanisms, and FHIR-based data access norms.

## Glossary

|=======================================================================
| Term             | Definition
| SMART on openEHR | This specification document detailing the SMART framework for an openEHR enabled platform
| SMART App Launch | The original SMART framework specified by HL7 FHIR, often referred as "SMART on FHIR"
| Vendor           | An entity that develops and supplies software to end-users.
| User             | The individual operating the Application to perform specific functions; also referred to as the "end-user".
| Application      | A software application developed by a Vendor to operate with a Platform and/or Launcher, potentially built by the same or a different Vendor. In OAuth terminology this is the "client", whereas in FHIR is often called the "SMART App".
| Platform         | A software ecosystem comprising at minimum an Authorization Server, an openEHR Clinical Data Repository (CDR), and a FHIR Server. It exposes openEHR REST APIs, FHIR APIs, and possibly other APIs. In FHIR this is often referred to as the "EHR system". The Platform includes the authentication and authorization infrastructure that supports OAuth 2.0 Framework and this specification.
| Launcher         | A user-facing application, typically developed by the Platform vendor, which initiates the launch of Applications within the context of a specific Patient or Practitioner. The Launcher may be integrated into the Platform's main application (e.g. as a Portal) or exist as an independent application.
| EHR              | A (session) context representing the {openehr_rm_ehr}#_ehr_package[openEHR `EHR` container^] for the corresponding Patient, indicating the subject of interactions through the Application.
|=======================================================================

====
The https://hl7.org/fhir/smart-app-launch/STU2.1/[SMART App Launch Framework^] specification uses the terms '_EHR_' and '_EHR system_' to describe a system comprising a FHIR Server, Authorization Server, and potentially other components, including a Launcher.

In contrast, openEHR defines an {openehr_rm_ehr}[EHR Information Model^], centered around the {openehr_rm_ehr}#_root_ehr_object[root `EHR` container^].

To avoid ambiguity, this specification reserves the term '_EHR_' exclusively for references to openEHR constructs (e.g., EHR type, EHR ID).
Alternate terminology will be used to describe equivalent FHIR-based system components.
====

## Why SMART on openEHR?

A widely accepted vision today is that no single software vendor can provide all the necessary tools and solutions required by a modern healthcare system, while simultaneously ensuring high quality and maintaining a low total cost of ownership.
Independent vendors, specializing in solving specific problems, often offer advantages over monolithic software suites attempting to address all needs.

In practice, this vision necessitates a collaborative ecosystem where applications from multiple vendors operate together to deliver a comprehensive solution.
This approach is often referred to as a "best-of-breed" architecture.
However, current implementations typically involve a lengthy and complex manual "integration" phase, during which vendors must coordinate their systems to interoperate, an expensive and time-consuming process that poses a significant barrier to entry for new vendors.

The SMART specification addresses this challenge by standardizing the security and interactions between systems and applications.
It establishes a clear contract between the _Application Vendor_ and the _Platform Vendor_, covering the following requirements:

- The _Application_ must be able to run on a domain owned by the _Application Vendor_.
- The _Platform_ must be able to operate on a domain owned by the _Platform Vendor_.
- The _Application_ must be able to discover the API services provided by the _Platform_.
- The _Application_ must be able to authenticate with the _Platform_ to access its APIs.
- The _Platform_ must be able to authorize the _Application_ for specific actions and data access, based on user roles and granted scopes.
- The _Application_ must be able to determine the active operational "context" managed by the _Platform_, such as the current EHR.
- The _Application_ must be able to embed within the _Platform_'s user interface while maintaining the current context to ensure a seamless user experience.

The *SMART on openEHR* specification is designed to maintain compatibility with https://hl7.org/fhir/smart-app-launch/STU2.1/[SMART App Launch Framework^], while extending it to work with {openehr_its_rest_releases}[openEHR REST APIs^] and potentially other API types.
It defines a framework supporting the following capabilities:

* [Application Registration](#_application_registration)
* [Service Discovery](#_service_discovery)
* [Authentication](#_authentication)
* [Authorization](#_authorization)
* [Scopes](#_scopes)
* [Context Selection](#_context_selection)
* [Embedded iFrame Launch](#_embedded_iframe_launch)

## Foundational Concepts

The {openehr_rm}[openEHR Reference Model^] and the {openehr_ehr_rest_api}[openEHR REST API specification^] provide the foundational structure for interoperable _Applications_.
For these applications to be truly portable across systems and vendors, a standardized approach to _authentication_ and _authorization_ is essential.

_Authentication_ is the process of verifying the identity of an end-user or client application, while _Authorization_ is the process of determining what access or privileges that entity has.

The *SMART on openEHR* specification builds on the {ietf_html}/rfc6749[OAuth 2.0 Framework^] and optionally https://openid.net/specs/openid-connect-core-1_0.html#Authentication[OpenID Connect (OIDC)^], to allow third-party applications to securely obtain authorized access to protected healthcare data exposed as APIs by the _Platform_.

Moreover, many such applications operate within the _context_ of a specific Patient or a particular Episode.
Therefore, selection of the appropriate _context_ becomes a critical prerequisite for launching the _Application_.

# Application Registration

Before an _Application_ can integrate with a _Platform_, it must first be registered.
This registration process establishes a trusted relationship between the _Application Vendor_ and the _Platform Vendor_, and includes the configuration of necessary parameters for authentication, authorization, and launch.

The registration process includes the following steps:

- The _Application_ registers with the _Platform_ by submitting metadata such as:
* Application name, logo and identifier
* Authorized domains and redirection URIs (`redirect_uri`)
* Supported launch contexts (e.g., patient, practitioner)
* Application type (e.g., confidential or public client)
* Client JSON Web Keys (JWKs) or a JWK Set URL
* Requested OAuth 2.0 scopes
- Upon successful registration, the _Platform_ issues credentials to the _Application_, such as:
* A unique `client_id` (always required)
* A `client_secret` (for confidential clients)
* Optionally, a set of JSON Web Keys (JWKs) or a JWK Set URL (`jwks_uri`) for JWT-based client authentication

These credentials are used in subsequent OAuth 2.0 flows to authenticate the _Application_ and enable secure, scoped access to protected resources.

The https://hl7.org/fhir/smart-app-launch/STU2.1/client-confidential-asymmetric.html#registering-a-client-communicating-public-keys[SMART App Launch Framework^] describes a corresponding registration flow, including support for registering public keys using `jwks` or `jwks_uri` to enable secure client authentication. The *SMART on openEHR* specification adopts a compatible approach, extending these mechanisms for use with openEHR-based APIs and platforms.

While this registration process could be formalized and automated using the {ietf_html}/rfc7591[OAuth 2.0 Dynamic Client Registration Protocol^], the current recommendation is to handle registration out-of-band in a way that is practical for both the Application Vendor and the Platform Vendor.
For example, the _Platform_ may provide a dedicated registration portal where _Application Vendors_ can submit their applications for review. This portal may support approval workflows, audit trails, and administrative oversight before issuing credentials, ensuring that only vetted applications are authorized to interact with the Platform.
# Service Discovery

A _Platform_ typically exposes multiple service endpoints.
These include OAuth 2.0 endpoints such as Authorization and Token, standard data service endpoints (e.g., openEHR REST APIs, FHIR APIs), and possibly other standard or proprietary APIs (e.g. DICOMWeb APIs).

The *SMART Service Discovery* mechanism extends the https://hl7.org/fhir/smart-app-launch/STU2.1/conformance.html#using-well-known[FHIR `.well-known/smart-configuration`^] endpoint definition.
It allows a _Platform_ to advertise [authentications](#_authentication_endpoints) endpoint, SMART [capabilities](#_capabilities), and a list of available [services](#_services).

.SMART Service Discovery
image::{doc_name}/diagrams/smart_service_discovery.svg[id=smart_service_discovery, align="center"]

The configuration endpoint should be always available relative to the _Platform_ base URL.
For example, given a base URL as `\https://platform.example.com`, the SMART configuration endpoint must be available at `\https://platform.example.com/.well-known/smart-configuration`.
If the base URL includes a path segment as `\https://platform.example.com/gateway/v1`, then the configuration should be accessible at `\https://platform.example.com/gateway/v1/.well-known/smart-configuration`.

Unlike the https://hl7.org/fhir/smart-app-launch/STU2.1/conformance.html#using-well-known[FHIR `.well-known/smart-configuration`^], which defines the configuration endpoint relative to the base URL of the FHIR server, this specification defines this endpoint relative to the _Platform_ base URL (i.e. the gateway).
This allows the _Platform_ to advertise service capabilities beyond FHIR APIs, including openEHR REST APIs and other APIs that may not be part of the FHIR server itself.
While this provides greater flexibility and aligns with a multi-API architecture, _Platform_ vendors are encouraged to ensure compatibility with SMART FHIR applications by maintaining a consistent `issuer` and exposing the FHIR API at the same base URL when feasible.

====
In order to maintain compatibility with SMART App Launch, it is recommended that the base URL of the _Platform_ also acts as the base URL of the FHIR server.
Such applications often assume the `iss` (issuer) launch parameter is both the base FHIR endpoint and the `issuer` value in the configuration document.
_Platform_ vendors may implement this alignment using gateways, proxies, or redirection mechanisms. However, such implementation details are outside the scope of this specification.
====

Responses to `/.well-known/smart-configuration` endpoint must be served with the `application/json` MIME type. A representative example is shown below:

```json
{
  "issuer": "https://platform.example.com",
  "jwks_uri": "https://platform.example.com/.well-known/jwks.json",
  "authorization_endpoint": "https://platform.example.com/auth/authorize",
  "token_endpoint": "https://platform.example.com/auth/token",
  "services": {
    "org.openehr.rest" : {
      "baseUrl":"https://platform.example.com/openehr/rest/v1",
      "description": "The openEHR REST APIs baseUrl",
      "documentation": "https://example.com/openehr/docs",
      "openapi": "https://example.com/openehr/rest/v1/openapi.json"
    },
    "org.fhir.rest" : { 
      "baseUrl":"https://platform.example.com/",
      "description": "The FHIR APIs baseUrl"
    },
    "com.amazon.aws.s3.rest": {
      "baseUrl":"https://s3.example.com/storage",
      "documentation": "https://example.com/s3/docs",
      "openapi": "https://example.com/s3/openapi.json"
    },
    "com.example.demographics": {
      "baseUrl":"https://demographics.example.com/rest"
    }
  },
  "token_endpoint_auth_methods_supported": [
    "client_secret_basic",
    "private_key_jwt"
  ],
  "grant_types_supported": [
    "authorization_code",
    "client_credentials"
  ],
  "registration_endpoint": "https://platform.example.com/auth/register",
  "scopes_supported": ["openid", "profile", "launch", "launch/patient", "patient/*.rs", "user/*.rs", "offline_access"],
  "response_types_supported": ["code"],
  "management_endpoint": "https://platform.example.com/user/manage",
  "introspection_endpoint": "https://platform.example.com/user/introspect",
  "revocation_endpoint": "https://platform.example.com/user/revoke",
  "code_challenge_methods_supported": ["S256"],
  "capabilities": [
    "launch-ehr",
    "permission-patient",
    "permission-v2",
    "client-public",
    "client-confidential-symmetric",
    "context-ehr-patient",
    "sso-openid-connect",
    "context-openehr-ehr",
    "openehr-permission-v1",
	"launch-base64-json"
  ]
}
```

The details of the `/.well-known/smart-configuration` are described in the sections below.

## Authentication Endpoints

The following attributes in the `.well-known/openid-configuration` must match those defined in the OAuth 2.0 + https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Connect Discovery^] specification as well as the {hl7_fhir}/smart-app-launch/conformance.html#metadata[FHIR SMART metadata^] specification:

- `issuer`
- `jwks_uri`
- `authorization_endpoint`
- `grant_types_supported`
- `token_endpoint`
- `token_endpoint_auth_methods_supported`
- `registration_endpoint`
- `scopes_supported`
- `management_endpoint`
- `response_types_supported`
- `introspection_endpoint`
- `revocation_endpoint`
- `capabilities`
- `code_challenge_methods_supported`

## Services

In addition to the {hl7_fhir}/smart-app-launch/conformance.html#metadata[FHIR-specific metadata^], the response from configuration endpoint must include the `services` section describing the available service interfaces exposed by the _Platform_.
This section enables Applications to dynamically discover the APIs provided by the _Platform_, along with their respective base URLs, descriptions, and potentially documentation links.

The `services` is a hash map, where each key is a reverse domain name uniquely identifying a service (e.g., `org.openehr.rest`), and the corresponding value contains the service-specific metadata and base URL. This structure allows for a flexible and extensible way to declare multiple APIs that may coexist within the _Platform_.

At a minimum, the `services` section must include the openEHR REST API using the key `org.openehr.rest`.
For consistency reason, it is also recommended to include the FHIR API under the key `org.fhir.rest`:

* `org.openehr.rest`: The base URL of the openEHR REST APIs `*(required)*`
* `org.fhir.rest`: The base URL of the FHIR APIs `*(recommended)*`

Additional services, such as CDS Hooks endpoints, terminology services, or non-RESTful interfaces, may be included using appropriately namespaced keys. For example:

* `org.dicomstandard.dicomweb.rest`: DICOMWeb REST API endpoint
* `com.amazon.aws.s3.rest`: AWS S3-compatible REST API
* `com.example.demographics`: A vendor-specific demographic service

Each service definition may contain:

- `baseUrl`: Absolute URL to the root of the API `*(required)*`
- `description`: Human-readable description of the service
- `version`: Service API version
- `documentation`: Link to service documentation
- `openapi`: Link to the OpenAPI (Swagger) definition of the API

Example:

```json
{
    "org.openehr.rest" : {
        "baseUrl": "https://platform.example.com/openehr/rest/v1",
        "description": "The openEHR REST API baseUrl",
        "documentation": "https://platform.example.com/openehr/docs",
        "openapi": "https://platform.example.com/openehr/rest/v1/openapi.json"
    }
}
```

## Capabilities

The `capabilities` section advertises supported SMART features as an array value. In addition to those scopes defined in the original https://hl7.org/fhir/smart-app-launch/STU2.1/conformance.html#capabilities[SMART App Launch^] framework, the following capabilities extend the list for openEHR platforms:

* `context-openehr-ehr`: Indicates support for EHR-level launch context, requested via `launch/patient` scope and conveyed via the `ehrId` token claim.
* `context-openehr-episode`: Indicates support for Episode-level context, requested via `launch/episode`, scope conveyed via `episodeId` ([experimental](#_experimental_episode_context)).
* `openehr-permission-v1`: Indicates support for fine-grained [scopes](#_resource_scopes) and authorization scheme over openEHR resources.
* `launch-base64-json`: Indicates support for encoding launch context as a base64-encoded JSON object in the `launch` parameter.
# Application Types

The appropriate authentication flow depends on the type of the client _Application_, particularly its ability to securely manage credentials and the nature of its interaction with users or backend services. The *SMART on openEHR* specification defines two fundamental client types based on credential handling capabilities, and further distinguishes applications by their interaction model.


## Classified by Credential Handling

The following client application types are defined by the https://hl7.org/fhir/smart-app-launch/STU2.1/app-launch.html#support-for-public-and-confidential-apps[considered by SMART specification^] based on their ability to securely manage secrets or to secure the client authentication using other means:

- **Confidential applications**:
These applications can securely hold credentials such as a `client_secret` or private keys. This category includes backend services, server-side web applications, and applications using hardware security modules or additional technology for higher security.

- **Public applications**:
These applications cannot securely store secrets. This includes native mobile apps and single-page web applications (SPAs) running in browsers. For these apps, authentication must rely on flows that do not require client credentials (e.g., PKCE).

The distinction between _public_ and _confidential_ clients is essential in determining the appropriate OAuth2 flow, and impacts which tokens can be safely issued and under what conditions.


## Classified by User Interaction

Applications are also classified by the context in which they are launched and the nature of their end-users:

- **Patient-facing applications**:
These applications are used directly by the patient, or are launched by a practitioner in the context of a specific patient. Optionally, the launch may be tied to a particular episode of care.

- **Practitioner-facing applications**:
These applications are used by healthcare professionals and may operate within or outside the context of a specific patient or episode.

- **Backend services**:
These applications operate autonomously without direct user interaction. They are typically used for system-to-system communication or background processing, such as synchronization, analytics, or alerts.


# Authentication

In line with the SMART framework, authentication is typically an integral part of the OAuth 2.0 authorization process.
For verifying end-user identity, an external identity provider is expected, typically using https://openid.net/specs/openid-connect-core-1_0.html#Authentication[OpenID Connect (OIDC)^].
While OIDC is the recommended approach, the exact mechanisms of identity verification are considered implementation-specific and fall outside the scope of this specification.

## Supported Authentication Flows

Client _Applications_ may authenticate with the _Platform_ using one of the following OAuth2-compatible flows.
The choice of flow depends on the [client application type](#_application_types) (public vs. confidential) and the desired security posture.

* {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] with {ietf_html}/rfc7636[Proof Key for Code Exchange (PKCE)^]:
Recommended for public clients (e.g., browser or mobile apps) as it does not require a client secret and mitigates interception risks.

* {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] with `client_secret`:
Suitable for confidential clients, such as backend web applications capable of securely storing secrets.

* {ietf_html}/rfc6749#section-1.3.4[Client Credentials Grant^]:
Used when no end-user is involved (e.g., background system-to-system communication).

* {ietf_html}/rfc7523[JWT Bearer Token Grant^]:
Preferred for confidential clients using asymmetric keys (e.g., JSON Web Keys) to authenticate via signed JWTs in accordance with {ietf_html}/rfc7515[JSON Web Signature (JWS)^].

_Platform_ implementation must clearly advertise which flows are supported in its `.well-known/smart-configuration` metadata document. This allows clients to dynamically determine how to authenticate and obtain tokens.

## Client Authentication Methods

SMART distinguishes two main authentication methods for confidential clients:

* https://hl7.org/fhir/smart-app-launch/STU2.1/client-confidential-asymmetric.html[Asymmetric Authentication^]:
The preferred method in SMART framework. This approach avoids transmitting shared secrets. It leverages either the {ietf_html}/rfc6749#section-1.3.4[Client Credentials Grant^] or the {ietf_html}/rfc7523[JWT Bearer Token Grant^], using public/private key pairs (e.g., JSON Web Keys) for authentication.
* https://hl7.org/fhir/smart-app-launch/STU2.1/client-confidential-symmetric.html[Symmetric Authentication^]:
This approach is simpler but less secure and uses a pre-shared `client_secret` to authenticate. Typically used with the {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] flow.


## Deprecated Flows

The following OAuth 2.0 flows are discouraged and MUST NOT be used within SMART on openEHR due to security concerns:

- {ietf_html}/rfc6749#section-1.3.2[Implicit Grant^]: Exposes tokens in the URL and lacks proper confidentiality guarantees.
- {ietf_html}/rfc6749#section-1.3.3[Resource Owner Password Credentials Grant^]: Involves direct transmission of user credentials and does not support modern identity federation.


## Flow Recommendations

The following recommendations apply based on client type and use case:

- **Public clients** should use the {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] with {ietf_html}/rfc7636[Proof Key for Code Exchange (PKCE)^] exclusively. This flow offers strong security without requiring client secrets.
- **Confidential clients** may use the {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] with {ietf_html}/rfc7636[Proof Key for Code Exchange (PKCE)^], or the {ietf_html}/rfc6749#section-1.3.1[Authorization Code Grant^] with `client_secret`, depending on security infrastructure.
- **Backend services** must use a confidential client and are recommended to use the {ietf_html}/rfc7523[JWT Bearer Token Grant^] (preferred) or the {ietf_html}/rfc6749#section-1.3.4[Client Credentials Grant^], depending on the level of trust and identity requirements.

These flows ensure secure and appropriate access to the _Platform_ based on the capabilities and deployment context of the application.

The table below illustrates recommended flows for common application scenarios:

|=======================================================================
| Application Example | Client Type | User Interaction Type | Recommended Flow
| Single Page Web Application for a Patient Portal | Public | Patient-facing | Authorization Code Grant with PKCE
| Mobile Application for Tracking Heart Rate | Public | Patient-facing | Authorization Code Grant with PKCE
| Web Application with Backend for Cardiology Management | Confidential | Practitioner-facing | Authorization Code Grant with PKCE or Authorization Code Grant with `client_secret`
| Realtime Alert System for Hospital | Confidential | Backend service | JWT Bearer Token Grant with JWS or Client Credentials Grant
|=======================================================================


# Authorization

Both *patient-facing* and *practitioner-facing* applications have specific authorization requirements that extend beyond the capabilities of the core {ietf_html}/rfc6749[OAuth 2.0 Authorization Framework^].
Depending on how an application is invoked, SMART Framework https://hl7.org/fhir/smart-app-launch/STU2.1/app-launch.html#smart-authorization\--fhir-access-overview[defines two launch^]  contexts, enabling apps to obtain contextual access to clinical data based on the user and their session:

1. *Standalone Launch*: The _Application_ is initiated directly by the end-user, outside the context of a running session on the _Platform_. For example, the user may visit `\https://myapp.example.com` and select the Platform instance they want to connect to. The _Application_ then begins the SMART authorization sequence using the selected Platform’s base URL and `.well-known/smart-configuration` metadata.
2. *EHR Launch*: The _Application_ is launched from within the Platform’s user interface (typically within an `iframe` within a Portal). The _Platform_ passes the `iss` (issuer) and `launch` parameters to the Application, such as in `\https://myapp.example.com?launch=123&iss=https://platform.example.com`. The `iss` identifies the Platform (FHIR server), and the `launch` parameter conveys session-specific information used to retrieve additional context data.

====
To avoid confusion with the {openehr_rm_ehr}#_ehr_package[openEHR Reference Model's `EHR`^] class, the *EHR Launch* is in this document referred to as an *Embedded iFrame Launch*.
====


## SMART Authorization Flow

The SMART framework builds on the {ietf_html}/rfc6749#section-4.1[OAuth 2.0 Authorization Code Flow^] and defines several SMART-specific launch enhancements on how to https://hl7.org/fhir/smart-app-launch/STU2.1/app-launch.html#obtain-authorization-code[obtain the authorization code^]:

1. The _Application_ redirects the user to the Platform's `authorization_endpoint`, including SMART-specific query parameters such as `aud`, `launch`, `scope`, `state`, `redirect_uri`, etc.
2. The _Authorization Server_ authenticates the user, validates the requested scopes, and (if allowed) issues an authorization `code` to the Application via the `redirect_uri`.
3. The _Application_ exchanges the authorization `code` for an `access_token` and optionally an `id_token` and `refresh_token` by POSTing to the Platform’s `token_endpoint`.


## Context Selection

In a *Standalone Launch*, a client _Application_ can request the _Platform_ to assist with _context_ selection, provided that the relevant [capabilities](#_capabilities) are supported by the _Platform_.
Most *patient-facing* and *practitioner-facing* applications will require the _Platform_ to supply additional context during the authorization process.
This contextual data may include identifiers such as the openEHR EHR ID, FHIR Patient ID, Episode ID, etc. The context is typically valid for the duration of the user session.

.Standalone Launch
image::{doc_name}/diagrams/smart_standalone_launch.svg[id=smart_standalone_launch, align="center"]

The purpose of this _context_ data is to pre-load or configure the _Application_ to operate within a relevant clinical scope.
The _Platform_ may determine this context automatically based on the authenticated user, or may prompt the user (e.g., via a selection screen) after the consent page if multiple valid contexts are possible.

To explicitly request openEHR-related launch context, the _Application_ must include the following SMART-defined *scopes* in the authorization request:

|=======================================================================
| Scope | Meaning
| `launch/patient` | Indicates that the Application requires patient context at launch (both FHIR `Patient` resource and corresponding openEHR `EHR` instance). For Standalone Launch, the user should be prompted to select the openEHR `EHR`.
| `launch/episode` | Indicates that the Application requires episode context at launch. ([Experimental](#_experimental_episode_context))

|=======================================================================

The _Platform_ returns the resolved context information in the token response, alongside the `access_token` and optionally an `id_token`. In addition to the standard https://hl7.org/fhir/smart-app-launch/STU2.1/scopes-and-launch-context.html#launch-context-arrives-with-your-access_token[SMART App Launch context attributes^], the following openEHR-specific parameters may be included in the token response:

|=======================================================================
| Parameter | Meaning
| `ehrId` | The unique identifier of the openEHR `EHR` instance associated with the selected FHIR `Patient` resource.
| `episodeId` | The identifier of the selected clinical episode (if applicable). ([experimental](#_experimental_episode_context))

|=======================================================================

The Application may use these parameters to tailor the user interface and functionality to the selected clinical context.

====
While this specification defines openEHR-specific launch parameters, standard SMART launch scopes and context attributes remain compatible and may be used in parallel for interoperability purposes. These are referenced from the https://hl7.org/fhir/smart-app-launch/STU2.1/scopes-and-launch-context.html[SMART App Launch Framework^], but their use is not normative in this specification.
====


## Embedded iFrame Launch

Many *practitioner-facing* applications and, in some cases, *patient-facing* applications are integrated directly within a web-based front-end (e.g., a clinical portal or patient portal) using a dedicated component.

In an *Embedded iFrame Launch*, the _Platform_ initiates the application by embedding it in an `iFrame` and passing key parameters directly in the URL:

- `launch`: An opaque identifier or [token](#_launch_parameter_as_a_token) that encodes relevant launch context (e.g., patient, EHR ID, episode).
- `iss`: The issuer URL representing the _Platform's_ base endpoint (which, for compatibility with SMART on FHIR, should also serve as the FHIR base URL).

For example, an application might be launched by: `\https://myapp.example.com?launch=123&iss=https://platform.example.com`.

.Embedded iFrame Launch
image::{doc_name}/diagrams/smart_embedded_iframe_launch.svg[id=smart_embedded_iframe_launch, align="center"]

Once launched, the _Application_ uses the `iss` value to retrieve the SMART configuration document from `{iss}/.well-known/smart-configuration`.

This configuration document provides important endpoints including the `authorization_endpoint`.
The _Application_ uses this information to initiate the {ietf_html}/rfc6749#section-1.3.1[OAuth 2.0 Authorization Code Flow^], including the `launch` parameter in the authorization request.

To support this interaction model, the following SMART-defined *scope* must be also included in the authorization request:

|=======================================================================
| Scope | Meaning
| `launch` | Permission to obtain launch context when Application is launched from an EHR (i.e., Embedded iFrame Launch).
            Must be accompanied by the `launch` parameter in the authorization request.
|=======================================================================


# Scopes

Authorization is governed by *scopes*, which define the type and extent of access that a client _Application_ is requesting from the _Platform_.

As specified in {ietf_html}/rfc6749#section-3.3[OAuth 2.0 Section 3.3^], scopes are passed during the authorization request and are evaluated by the _Platform_ when issuing access tokens.
The _Platform_ must validate requested scopes against the _Application_ registration metadata, applicable access control policies, the authenticated user's permissions.

*SMART on openEHR* aligns with FHIR's https://hl7.org/fhir/smart-app-launch/STU2.1/scopes-and-launch-context.html[SMART App Launch Framework^], where scopes serve three main purposes:

- **Resource Access**: Grant access to specific resource types (e.g., `patient/composition-\*.rs`).
- **Context Declaration**: Request specific launch contexts (e.g., `launch/patient`).
- **Identity Claims**: Enable OpenID Connect scopes (e.g., `openid`) to identify the user.

## Resource Scopes

The _Application_ can request access to the _Platform_ resources using the scope syntax `<compartment>/<resource>.<permission>` where:

- `<compartment>` indicates the scope of access delegation:
  * `patient`: Access is limited to the current EHR and Patient is present in the context.
  * `user`: Access is granted based on the authenticated user's permissions.
  * `system`: Access is granted to backend applications acting without a user context.
- `<resource>` identifies the openEHR or derived asset being accessed.
- `<permissions>` specifies the allowed operations.

The following `<compartment>` are supported:

- `patient`: For applications acting in the context of a specific patient/EHR. Access is restricted to data within that patient's EHR.
- `user`: For applications acting on behalf of a logged-in user (e.g., a practitioner). Access is subject to the user's security profile, not limited to the Patient in context (if any is present).
- `system`: For server-to-server integrations or backend services, typically using client credentials, based on pre-configured client-specific policy. Grants access across all data.

The following {openehr_its_rest_releases}[openEHR REST APIs] `<resource>` types are supported for use in scopes:

- `template-<templateId>` - Access to operational templates matching `<templateId>` expression.
- `composition-<templateId>` - Access to compositions of a given template matching `<templateId>` expression.
- `aql-<queryName>` - Access to pre-defined (matching `<queryName>` expression) or ad-hoc (using wildcard `*`) AQL queries.

The `<templateId>` and `<queryName>` support wildcard and pattern-based matching using `\*` and `**`, as follows:

|=======================================================================
| Pattern | Matches
| `MyHospital::Template.v0` | Template exact match only
| `org.openehr::bloodpressure.v1` | Query exact match only
| `*::Template.v0` | Template.v0 from any namespace
| `MyHospital::*` | Any template within MyHospital namespace
| `*` | All available templates or queries
|=======================================================================

The following permission expressions are supported:

- `c` - Create
- `r` - Read
- `u` - Update
- `d` - Delete
- `s` - Search or execute (e.g., for AQL queries)

====
Wildcard-based scopes (e.g., `\*` or `**`) should be used cautiously and only when absolutely necessary, as they imply broad access. For example, `system/aql-*.rs` would grant access to all registered and ad-hoc AQL queries system-wide.
====

The following table is a maximal representation of the scopes made possible in different _compartment_, _resource_ and _permission_ combinations:

|=======================================================================
| Scope | Description
| `patient/composition-<templateId>.crud` | Full CRUD access to compositions matching `<templateId>` in the current patient's EHR.
| `user/composition-<templateId>.crud` | Full CRUD access to compositions accessible by the user.
| `system/composition-<templateId>.crud` | Unrestricted CRUD access to compositions across the entire system.
| `user/template-<templateId>.crud` | Create and manage templates accessible to the user.
| `system/template-<templateId>.crud` | Full system-wide template management.
| `patient/aql-<queryName>.rs` | Execute and read AQL queries on the patient's EHR data.
| `user/aql-<queryName>.cruds` | Full access to user-permitted AQL definitions or ad-hoc queries.
| `system/aql-<queryName>.cruds` | System-wide access to AQL queries and endpoints.
|=======================================================================

# Experimental features

The following concepts and aspects are considered experimental.

====
Implementers should treat its use as provisional and subject to change in future versions of this specification.
====

## Launch Parameter as a Token

To support efficient and context-rich embedded launches, it is *recommended* that the `launch` parameter be a **base64-encoded JSON object** containing launch context attributes such as:

- `ehrId` - The openEHR EHR identifier
- `patient` - FHIR Patient ID (if available)
- `episodeId` - Clinical episode ID (optional)

This allows the _Application_ to initialize its interface with full context and potentially bypass a full authorization cycle if it is already authenticated.
This significantly improves the user experience, for instance, when switching patients within the same embedded session.

Platforms that support this optimization should advertise the following capabilities in their `/.well-known/smart-configuration` response:

- `launch-base64-json`: May be used to deliver context (including `episodeId`) in a base64-encoded JSON format for embedded iFrame launches.


## Experimental: Episode Context

The *Episode* concept represents a bounded period of care or clinical workflow, such as a hospital admission, treatment course, or referral. It serves as a logical container for grouping related clinical activities, encounters, and observations. This concept is particularly relevant for workflows where context must be maintained across multiple interactions or systems.

In the context of SMART on openEHR, Episode selection and usage is considered **experimental**.
While the openEHR specification outlines the concept of an Episode, formal resource definitions and operational semantics are still evolving.
As the openEHR specification evolves to formalize Episode as a first-class resource, the following enhancements may be introduced:

- Standardized resource representation of an Episode type or new archetype.
- Extended query support for filtering by Episode.
- Improved UI/UX support in authorization servers for Episode selection.
- FHIR mapping for Episode-related concepts.

This section outlines the current capabilities and usage patterns under evaluation for Episode support.

### Scopes and Capabilities

To request Episode context during an authorization flow, the following scope may be included in the authorization request:

|=======================================================================
| Scope | Description
| `launch/episode` | Requests Episode context at launch time. If launching outside an EHR, prompts the _Platform_ to determine or allow selection of the Episode relevant to the session.
|=======================================================================

Platforms that support Episode context should advertise the following capabilities in their `/.well-known/smart-configuration` response:

- `context-openehr-episode`: Indicates that the _Platform_ supports Episode context selection during launch, requested via `launch/episode` scope.

### Token Response Parameters

When an authorization request includes `launch/episode` scope and the Platform is capable of resolving the Episode, the following parameter will be included in the token response:

|=======================================================================
| Parameter | Description
| episodeId | Identifier of the selected or inferred Episode for the session. This may map to an openEHR EHR_STATUS.episode or a platform-specific abstraction. Its semantics are currently implementation-defined.
|=======================================================================

This value is intended to be used by the client Application to filter or group clinical data relevant to the specific Episode of care.

### Launch Scenarios

Standalone Launch:
When the `launch/episode` scope is included, the Platform may prompt the user to select an Episode or infer it automatically based on session context (e.g., currently admitted case, recent discharge summary, etc.).

Embedded iFrame Launch:
Episode context may be embedded in a base64-encoded `launch` parameter provided at runtime. This can improve usability by avoiding a separate Episode selection prompt during intra-portal navigation.



:sectnums!:

## References

* SMART App Launch - Release 2.1.0 (2021), https://hl7.org/fhir/smart-app-launch/STU2.1
* The 'About SMART' page on SMART Health IT, https://smarthealthit.org/about-smart-2/
* OAuth 2.0 Authorization Framework, {ietf_html}/rfc6749
* OAuth 2.0 Dynamic Client Registration Protocol, {ietf_html}/rfc7591
* OpenId Connect (OIDC), https://openid.net/specs/openid-connect-core-1_0.html#Authentication
* JSON Web Token (JWT) Assertion, {ietf_html}/rfc7523
* JSON Web Signature (JWS), {ietf_html}/rfc7515
* Best Practices in Authorization for SMART on FHIR EHRs, https://docs.smarthealthit.org/authorization/best-practices


:figure-caption!:
.SMART™ and the SMART logos are trademarks of The Children's Medical Center Corporation. Used with permission.
image::{doc_name}/diagrams/smart_logo.svg[SMART,140,80,id=smart_logo,link=https://smarthealthit.org/]
