How SMART on FHIR access works between Keycloak and HAPI FHIR
A team that needs apps and clinicians to reach a HAPI FHIR server without shared credentials has to move access onto OAuth 2.0 tokens. The division of labor matters from the start: Keycloak issues the tokens and publishes the discovery document, while HAPI FHIR must validate those tokens and decide what each one may do. HAPI FHIR provides the building blocks for that second part, including authentication handling and the AuthorizationInterceptor, but it does not ship a packaged SMART on FHIR connector that links the two. HAPI FHIR's own security documentation states that it does not provide a single one-size-fits-all security layer, so the integration is something your team configures and owns.
In practice, a client app first reads the SMART configuration document from the authorization server, then obtains a token with the scopes it was granted, and then calls the FHIR server with that bearer token. Keycloak supplies the discovery endpoint, the token endpoint and the client and scope settings. On the HAPI FHIR side, a custom interceptor must check the token signature, issuer, audience and expiry, extract the scopes and patient or user context, and hand those to authorization rules. Scope names such as those in the SMART App Launch vocabulary carry no meaning to HAPI FHIR until your code maps them to resource types, compartments and operations. Confirm with your security team which of those claims your Keycloak realm will emit before you write the interceptor.
Decide early who owns each mapping: the Keycloak client and scope definitions, the claim-to-scope translation, and the rule set that enforces them. A mismatch between any two of these produces either silent over-access or unexplained denials. Plan a test pass that replays real token types against both allowed and denied requests, and confirm the Keycloak version and its supported release cadence against the Keycloak server administration guide before you fix the configuration.
What the team needs before configuring SMART access
SMART access touches two systems that must agree on versions, network paths, certificates and realm design before any scope is written. Confirm these items first, because a mismatch in any one of them shows up later as a token that validates in one place and fails in another.
Confirm the HAPI FHIR version
Start by confirming which HAPI FHIR version your server runs, since the interceptor code and configuration keys you write depend on it. HAPI FHIR 8.2.0 or later requires JDK 17, so check the Java runtime in your image or application server before anything else. Record the version in your change ticket so the interceptor build matches the running server.
HAPI FHIR versionsPin the Keycloak release
Keycloak 26.8.1 is the current release, so decide whether you deploy it or a tested minor line in your environment. Since Keycloak 26.0, breaking changes in a minor release are opt-in, which makes an upgrade plan easier to schedule. Ask who will own Keycloak upgrades before the realm design starts.
Keycloak release updatesChoose a supported production database
Keycloak stores realms, clients and sessions in a database, and the development file database is for development only. For production, PostgreSQL 14 to 18 is supported, along with several other engines. If your Keycloak cluster needs high availability, confirm the database supports synchronous replication, because both supported HA designs depend on it.
Keycloak database guideMap network paths between the servers
The FHIR server must reach the Keycloak issuer to fetch its discovery document and signing keys, and clients must reach Keycloak for login. Write down each path, including which DNS names resolve inside and outside your network, and whether a proxy sits in between. Ask the network team to confirm egress rules from the FHIR server subnet before testing.
Plan TLS certificates and trust
Issuer URLs, token endpoints and JWKS URIs must use certificates that the FHIR server's Java truststore accepts, including any internal certificate authority. Confirm the certificate names match the hostnames in the issuer URL exactly, since a mismatch fails token validation silently in some setups. Decide who renews these certificates and how a renewal reaches the Java truststore.
Define the clinical apps realm
Create a dedicated Keycloak realm for clinical applications rather than reusing a workforce realm, so client scopes, token lifetimes and user federation stay separate. Decide which user sources feed the realm, such as an existing directory, and which clients need confidential or public configuration. Record the realm name and issuer URL, because the FHIR server configuration will reference both.
Keycloak server administrationDecide how Keycloak is deployed
Choose between the Keycloak Operator, the experimental Helm chart and a Docker-based deployment. The Operator is installed through Operator Lifecycle Manager and manages Keycloak and client custom resources, and its documentation strongly recommends manual approval mode for updates. Whichever method you choose, assign an owner for the realm configuration so it is versioned and not edited by hand in production.
Keycloak Operator installationConfiguration sequence for SMART on FHIR with Keycloak
This sequence turns a HAPI FHIR server and a Keycloak realm into a working SMART on FHIR authorization path, where each step ends with a check you can run before moving on. Work through it in a test environment first, then repeat it in your production realm and cluster.
Create the Keycloak realm and clients
The identity team creates a dedicated realm for the FHIR server, then registers one client for each app type you plan to support, such as a confidential backend service and a public browser app that uses PKCE. Set the redirect URIs and the allowed web origins from your app inventory, and keep test and production realms separate. Done means the realm's OpenID Endpoint Configuration document loads over HTTPS and lists the token and authorization endpoints your apps will call. Confirm the issuer value exactly, because the FHIR server will compare it against token claims.
Define client scopes that match SMART names
Create Keycloak client scopes whose names follow the SMART App Launch pattern, such as the patient and user scope families with resource type and permission suffixes, and attach them to the clients that need them. Decide which scopes are default and which are optional, and document the meaning of each one for your app developers and your security reviewers. Done means a test token requested with a given scope carries that scope in its scope claim. Decode the token once to confirm the claim is present and spelled the way your interceptor rules expect.
Expose the SMART discovery document from FHIR metadata
The FHIR team configures the HAPI FHIR server so its CapabilityStatement points to the SMART discovery information, which lets SMART-aware apps find the authorize and token endpoints without hard-coded values. Confirm the exact way your HAPI FHIR version exposes this in its documentation, because the configuration keys and the metadata structure depend on the version you run. Done means fetching the metadata endpoint returns a security section that references your Keycloak issuer and the well-known configuration path. Compare those URLs with the document from step one.
Configure the authentication interceptor for bearer tokens
The platform engineer adds an authentication interceptor to the HAPI FHIR JPA server that reads the bearer token from the Authorization header, checks the signature against the Keycloak signing keys, and validates the issuer, audience and expiry. Set the JWKS location and the expected issuer in configuration, and keep those values in your secrets store. Requests with no token or an invalid token should fail before any resource is read. Done means a request with a valid test token is accepted, and a request with a tampered or expired token returns an unauthorized status.
Map scopes into AuthorizationInterceptor rules
The security engineer writes AuthorizationInterceptor rules that translate each validated scope into allowed resource types, compartments and operations, and that deny anything the token does not cover. Start with read-only rules for the scopes your first apps need, then add write rules only after the read path is tested. Keep the rule set in version control so each change can be reviewed. Done means a test token with a read-only scope can search its permitted resources, while a write attempt or a resource outside its scope returns a forbidden status.
Verify denied and permitted requests end to end
The QA or security team runs a fixed set of test requests for each client type: a permitted read, a permitted search, a denied write, a denied resource type, and a request with a missing or stale token. Record the status code and response for each one, and repeat the set after every change to the realm, the interceptor settings or the rules. Done means every test matches the expected outcome in your written test plan. Keep the results with the change record, because auditors and internal reviewers will ask how access was checked before go-live.
Mapping Keycloak claims and SMART scopes to HAPI FHIR rules
This table traces one access decision from the SMART scope a client requests, through the Keycloak client scope or token claim that carries it, to the AuthorizationInterceptor rule and compartment check that enforces it. Read each row as a stage in that chain, and confirm the exact claim names in your own Keycloak mapper configuration before writing rules against them.
| Element | What it carries or does | Where it is configured | What to confirm |
|---|---|---|---|
| Patient scope (patient/*.rs) | Limits a client to resources in the launch patient's compartment for read and search | Requested scope in the app registration, granted by a Keycloak client scope | Which scopes your Keycloak client is allowed to request and how the server rejects unknown ones |
| User scope (user/*.read) | Ties access to the signed-in practitioner's own permissions across patients | Requested scope, checked against the user's roles or group membership | Whether user-level scopes are issued only when the user holds a matching role |
| Resource type and operation | Encodes resource type and read, write or search permissions in each scope | SMART scope string, mapped to rule operations in the interceptor | That write scopes map to create, update and delete operations, not only to POST and PUT |
| Patient context claim | Carries the launch patient ID so the interceptor can pin searches and reads to that patient | Keycloak protocol mapper that adds a custom claim to the access token | The exact claim name and format in your token, since it depends on your mapper configuration |
| User identity claim | Identifies the practitioner or system user for audit records and user-scope decisions | Standard subject claim or a mapper that adds a FHIR practitioner reference | Which claim holds the stable user identifier your audit and consent services read |
| Scope check against user grants | Ensures a requested scope is a subset of what the user may grant, not the full client registration | Keycloak client scopes and role assignments, evaluated at token issuance | That denied scopes are dropped or the request fails, and that the server re-checks scopes it receives |
| Allow rule | Permits a named operation on a resource type when the token holds the matching scope | AuthorizationInterceptor rule builder in the HAPI FHIR server | That allow rules are ordered and that the final deny-by-default rule is present |
| Deny rule and compartment check | Blocks requests whose resources fall outside the patient compartment in the token | AuthorizationInterceptor compartment checks, paired with search narrowing | Test against real request patterns, including chained searches and includes that cross compartments |
Security settings that keep SMART tokens meaningful
The authorization server decides which tokens exist, how long they last and who can change the configuration, so weak settings here undermine every control downstream. Start from the Keycloak production configuration guide rather than the development defaults, which are intended for local testing only. Keep the admin console on a separate hostname or restricted network path, enforce strong admin credentials with multi-factor authentication, and give operators named accounts with limited realm roles instead of a shared superuser. Review the metrics endpoint and confirm it is not reachable from public networks, because it exposes operational detail about the server.
- Production configuration: Run Keycloak in production mode with an external supported database and a hostname set explicitly, not inferred from request headers.
- Token lifetimes: Set short access token lifetimes and limit refresh token reuse so a stolen token has a narrow window of use. Confirm the values with your own risk owner.
- Client types: Use confidential clients for server-side apps and public clients with PKCE for browser and mobile apps. Disable flows that a client does not need, such as direct access grants.
- Admin console access: Restrict the admin console by network path and role, and log administrative changes.
- Metrics endpoint exposure: Bind the metrics and health endpoints to internal interfaces or protect them at the reverse proxy.
Check that every client, redirect URI and token setting matches a documented decision, and that changes go through the same review as application code.
Keycloak issues tokens, but the FHIR server is where access is actually granted or refused, so the enforcement layer has to be strict. Configure the authorization interceptor for default deny so that any request without an explicit allow rule fails. Validate every access token on each request: check the signature against the issuer's published keys, confirm the issuer matches the expected realm, and confirm the audience names this FHIR server. Reject tokens that carry scopes the server does not recognize rather than silently ignoring them, and log those rejections so misconfigured clients surface quickly. Map scopes to rules in a reviewed table, and test each mapping against the request patterns your applications actually send.
- Default deny: Start the authorization interceptor with no implicit allow, and add rules only for resource types, compartments and operations that are documented.
- Issuer validation: Match the token issuer to the exact realm URL from the discovery document, not a substring or a wildcard.
- Audience validation: Require the audience claim to name this server so tokens issued for other APIs in the same realm cannot be replayed here.
- Unknown scopes: Refuse tokens with scopes outside the mapped set and record the event.
- Key handling: Confirm the server can refresh signing keys after a Keycloak key rotation without a restart, and test that behavior.
Run negative tests with tokens from the wrong realm, wrong audience, expired lifetime and unmapped scope before go-live.
Tokens and FHIR data travel between browsers, applications, reverse proxies, Keycloak and HAPI FHIR, and each hop must protect them. Terminate TLS on every externally reachable service and use internal TLS or a trusted private network between the proxy and the application where your policy requires it. The reverse proxy must forward the original host and protocol headers so Keycloak and HAPI FHIR build correct URLs in discovery documents and redirects, and only trusted proxies should be allowed to set those headers. For browser-based SMART apps, configure CORS with an explicit list of allowed origins. Never combine a wildcard origin with credentials, because that combination lets any site read authenticated responses.
- TLS everywhere external: Serve Keycloak, the FHIR endpoint and the apps over HTTPS with current certificates managed by your certificate process.
- Proxy headers: Configure Keycloak to trust forwarded headers only from the proxy in front of it, and set the same rule on the FHIR server.
- Explicit CORS origins: List each allowed app origin, and allow credentials only where a browser flow needs them.
- No wildcard with credentials: Reject configurations that pair an asterisk origin with credential support.
- Token storage guidance: Tell app teams where tokens may live in the browser and keep them out of URLs and logs.
Verify the setup by sending requests from an unlisted origin and confirming the browser receives no permissive headers.
How a SMART app request reaches the FHIR server
The flow starts in the SMART app, which redirects the user's browser to Keycloak to sign in and request scopes. Keycloak returns an access token to the app, which then calls the HAPI FHIR server with that bearer token. Inside the server, an authentication interceptor checks the token against Keycloak's signing keys, and the AuthorizationInterceptor turns the granted scopes into allow or deny rules before any data is returned. Check the trust boundary: only the FHIR server should trust Keycloak's keys, and the app never handles FHIR data it is not scoped to read.
Token flow from SMART app through Keycloak to the HAPI FHIR server's interceptors.
Common failures when SMART tokens reach HAPI FHIR
This table lists the failures teams most often hit when a Keycloak-issued SMART token is presented to a HAPI FHIR server, with the usual cause and fix for each. Read it while testing the first end-to-end launch, and check each row against the token claims and server logs before changing rules.
| Failure | Likely cause | Fix |
|---|---|---|
| Token rejected with issuer mismatch | The token's iss claim reflects the public Keycloak hostname, but the interceptor is configured with an internal or proxy-side issuer URL, or the reverse proxy changes the host and scheme. | Set the Keycloak hostname and proxy headers so the issuer matches the value configured in HAPI FHIR, then confirm by decoding a test token. |
| Audience or client ID not accepted | The access token's aud claim or azp value does not match the audience or client identifier the server expects, often because a client scope or audience mapper was never added in Keycloak. | Add an audience mapper to the client in Keycloak and align the expected audience in the interceptor configuration with that value. |
| Token rejected as expired or not yet valid | Clock skew between Keycloak, the HAPI FHIR host and the proxy, so iat, nbf or exp checks fail near token boundaries. | Synchronize time on all hosts with NTP, review the allowed clock tolerance in the validator, and reproduce the failure with a short-lived token. |
| Requests succeed without a scope check | Scopes are missing from the token because the client did not request them, the realm default scopes were changed, or the mapper that emits the scope claim is absent. | Verify the scope claim in a decoded token, request the SMART scopes explicitly in the launch, and reject requests whose token carries no matching scope. |
| Requests bypass authorization checks | Interceptors are registered in an order where a permissive or pass-through interceptor runs before the authorization or token validation interceptor, or a path such as a metadata or operation endpoint is excluded. | Register token validation before AuthorizationInterceptor, list the interceptor order in configuration, and test denied requests against every resource type and operation. |
| Discovery document points to unreachable endpoints | The well-known configuration advertises internal hostnames, http instead of https, or paths that the reverse proxy does not route to Keycloak. | Correct the frontend URL and proxy settings in Keycloak, fetch the discovery document from outside the cluster, and confirm each advertised endpoint returns a response. |
| Launch client receives 401 on authorize redirect | The redirect URI registered on the Keycloak client does not exactly match the app's redirect, including trailing slashes or port numbers. | Register the exact redirect URIs for each SMART app and keep a test client separate from production clients. |
| Token accepted but patient scope is empty | The patient context claim is not added to the token, so patient-scoped rules have no patient to compare against. | Confirm the launch flow returns patient context and that the mapper writes it to the token, then test a patient-scoped read and a denied read for another patient. |
Questions teams ask before configuring SMART on FHIR
How much effort does SMART on FHIR authorization take to configure?
Effort depends mostly on how many SMART apps, scopes, resource types and compartments the server must govern. A single internal app reading a few resource types is a small job, while many apps with patient, user and system scopes across clinical resources is a much larger one. Each scope needs a matching rule in the AuthorizationInterceptor, each app needs a Keycloak client with its own redirect and scope settings, and each rule needs tests against real request patterns. Ask for the effort to be broken down by apps, scopes and resource types, because those counts are the main cost drivers.
Can an in-house team set this up without outside help?
A team with strong Java and FHIR experience and someone who has run Keycloak in production can build it, but the work crosses three disciplines: FHIR authorization, OAuth 2.0 and OpenID Connect configuration, and clinical access policy. Gaps usually appear in token validation edge cases, in mapping scopes to compartments correctly, and in testing denials, which are easy to miss. Teams should judge whether they have people covering each of those areas and time to test before go-live. DeployOpen can plan, implement and test this as a fixed-scope engagement if an internal build is not the right choice.
What do we need to provide during the engagement?
Plan for three groups of input from your side. FHIR administrators need to confirm the server version, the resource types in use and how the JPA server is deployed. Keycloak administrators need to provide or approve a realm, client registration practices and the identity source for users. Clinical or data rule owners need to define who may read which patient data, which apps are approved and what scopes they receive. You will also need representative test data and test user accounts that cover the roles you expect, including negative cases. Without the rule owners' decisions, the rules cannot be finished.
How long does it take to configure SMART on FHIR with Keycloak?
No duration has been established for this work, and the time depends on the scope described above, the state of your existing Keycloak and HAPI FHIR environments, and how many clinical rules need sign-off. Ask for a fixed-scope plan that lists the apps, scopes, resource types, environments and test cases covered, along with the milestones and the points where your owners must approve decisions. A plan built that way lets you compare options and see where delays would come from.
Is Keycloak required for SMART on FHIR on HAPI FHIR?
No. SMART App Launch style access needs an OAuth 2.0 authorization server that issues tokens with the scopes and launch context your apps expect, and HAPI FHIR validates those tokens through its authentication and authorization interceptors. Keycloak is a common, open-source choice because it supports OpenID Connect and OAuth 2.0 and can be run in infrastructure you control. Other authorization servers can work if they can issue the tokens and claims you need. Confirm the discovery document, token claims and scope format with whichever server you choose before writing rules.
What should a quote for this work include?
A quote should follow from a written scope and list each deliverable. Ask for the number of SMART apps and scopes in scope, the resource types and compartments covered by rules, the environments to be configured, and the Keycloak and HAPI FHIR versions assumed. Confirm whether the quote covers the discovery document and token validation, the rule set, test cases for allowed and denied requests, documentation and handover to your operators. Also ask which costs are one-time, such as build and testing, and which recur, such as Keycloak and server upgrades, support and periodic rule review.
What goes wrong most often with SMART on FHIR scopes?
The most common failures are scopes that are granted more broadly than the app needs, rules that allow a resource type but not its compartment, and tokens that are accepted without checking issuer, audience or expiry. Teams also find that search requests bypass rules that protect direct reads, so test both paths. Before go-live, confirm that denied requests return the expected status, that each app receives only its approved scopes and that rule changes are tested against recorded request patterns.
How DeployOpen scopes and delivers SMART on FHIR access
DeployOpen plans, builds, tests and hands over SMART on FHIR authorization for your HAPI FHIR server and Keycloak realm, inside infrastructure you control. Each engagement starts with a written scope that names the apps, scopes, rules and audit evidence in play, so your security and compliance teams can review the design before any build work begins.
How we scope
- Inventory the SMART apps, user types and FHIR resources that need access, and record which launch modes each app uses.
- Agree the scope list in writing: discovery document, Keycloak client and scope model, interceptor rules and test cases.
- Confirm with your identity team which Keycloak deployment, realm and external identity provider the design will use.
How we build
- Configure Keycloak clients and client scopes that map to SMART scope patterns for patient, user and system access.
- Implement token validation in a HAPI FHIR interceptor and connect scopes to AuthorizationInterceptor rules.
- Test allow and deny behavior against real request patterns, including expired tokens, missing scopes and cross-patient reads.
How we hand over
- Deliver configuration as code where possible, with a record of each client, scope and rule and why it exists.
- Document the discovery document endpoints, token lifetimes, key rotation steps and the runbook for adding a new SMART app.
- Provide a test report and the evidence your compliance team needs to review access control design.
How we support
- Ongoing support, upgrades and continuous testing are available as a retainer after handover.
- Plan Keycloak and HAPI FHIR upgrades against the release notes so rule changes are tested before they reach production.
- Ask for a quote that lists the scope items, the environments covered and the retest conditions before you sign.

