Narrowing HAPI FHIR searches to a user's patients
A clinical app or patient portal team usually needs one answer before any code is written: which patients each user may see, and what happens when a search asks for more. The SearchNarrowingInterceptor is HAPI FHIR's building block for the first half of that answer. It changes the result set of searches and conditional operations so they return only resources inside the compartments or value sets the user is permitted to reach, using criteria your code supplies. Teams need it when a request is legitimate but broad, such as a clinician searching Observation without a patient parameter, and they want the server to limit the answer instead of failing the call.
Narrowing and denying are different outcomes, and the difference matters for both security and client behavior. Narrowing returns a smaller set, so a broad search still succeeds and the client may not know that records were excluded. Denying refuses the operation outright, which is the job of the AuthorizationInterceptor. HAPI FHIR's security introduction states that it does not provide a single one-size-fits-all security layer and instead offers building blocks. Narrowing alone therefore cannot prove that a caller may invoke an operation at all. Plan both: authorization rules decide what a caller may do, and narrowing decides which rows come back.
Before relying on the interceptor, confirm in the version you run which compartments and value sets it honors, how it behaves with the search cache, with _include and with chained searches, and whether conditional create, update and delete are covered the same way. Test with requests your app actually sends, including searches with no patient parameter, paging links and direct reads by ID, because a direct read may not pass through a search-based filter. Run these checks on a test server with a known patient set, record the results, and keep the tests in your release pipeline so that an upgrade cannot quietly widen access.
Narrowing options and when each fits
This table compares compartment-based patient scoping, value set restrictions and partition-based separation for narrowing searches to a user's patients. Read each row for the access model it fits, the data it depends on and the cost it adds to queries and maintenance. Confirm each interceptor and partition behavior against the documentation for your HAPI FHIR version before you rely on it.
| Option | Access model it fits | Data it depends on | Trade-off in query behavior and maintenance |
|---|---|---|---|
| Compartment-based patient scoping | Clinicians or apps limited to one patient's records at a time | Resources linked to Patient by references the compartment definition covers | Searches gain a patient filter; confirm which resource types your version places in the Patient compartment |
| Value set restrictions | Access limited by category, such as selected code systems or sensitive classifications | Consistently coded elements and terminology loaded on the server | Large value set expansion can add query cost; updates to value sets need retesting |
| Partition-based separation | Multitenant deployments, separated data sources or regional grouping | A partition assigned to each resource at write time and tenant identification at the request | Strongest data boundary, but cross-partition searches and partition administration need explicit design |
| Authorization rules alone | Coarse control by resource type, operation or client scope | Identity claims, scopes or client context from the authentication layer | Rules judge each request, so broad searches still need narrowing alongside them |
| Compartment scoping with authorization rules | Patient-facing apps and clinician access tied to a care relationship | Patient linkage in the data and scope or patient context in the token | Two layers to test together; confirm how each layer handles conditional operations |
| Partitions with compartment scoping | Large deployments where each organization holds its own patient population | Partition design plus patient references inside each partition | More configuration and testing; cross-partition patient moves need a documented procedure |
| Value set restrictions with partitions | Organizations with regional rules for sensitive categories of data | Partition assignment, coded data quality and maintained value sets | Two rule sets to review on every terminology or policy change |
Setting up search narrowing with authorization rules
This sequence takes a HAPI FHIR JPA server from a bare deployment to one where each user's searches and conditional operations only reach the patients they are permitted to see. Each step ends with a check so the team can confirm the controls work before any real data is loaded.
Deploy the JPA server starter
Stand up the HAPI FHIR JPA server starter in a non-production environment, using the hapiproject/hapi Docker image, Docker Compose, or the Helm chart if you run Kubernetes. The embedded H2 default is only suitable for testing, so point the server at PostgreSQL or Microsoft SQL Server before you rely on any results. Your team owns the database, the container platform and the network path. Done means the server answers a metadata request and a test Patient can be created, read and searched without any security interceptors enabled, which gives you a baseline to compare against later.
Connect an external identity provider
Configure an OpenID Connect identity provider, such as Keycloak or another provider your organization already runs, and register the FHIR server or its client applications with it. The provider authenticates users and issues tokens, and the FHIR server validates those tokens through an authentication interceptor. Your identity team confirms which claims carry the user identity and any patient or role attributes. Done means a test user can obtain a token, and the server rejects a request with no token or an expired token while accepting a valid one.
Define the patient list for each user
Decide how each user's permitted patients are determined, for example from a claim, a lookup table maintained by your application, or a list of Patient or Group identifiers provided by your care or access systems. Document the source of truth, who maintains it, and how changes are removed when a care relationship ends. Keep the mapping in a form the interceptor can read at request time. Done means you have a written mapping for at least two test users with different patient lists, and both lists are reviewed by the data owner who will sign off on access.
Register the SearchNarrowingInterceptor
Register the SearchNarrowingInterceptor on the server so that searches and conditional operations are restricted to the compartments and values the user is permitted to reach. Configure it to use the patient list from the previous step, and confirm how it handles resource types that are not in a patient compartment. Test the setting on a dataset with known patients. Done means a search by the first test user returns only resources linked to that user's patients, and a broad search with no patient filter returns the same narrowed set rather than the full database.
Write matching AuthorizationInterceptor rules
Write AuthorizationInterceptor rules that match the narrowing logic, allowing the operations each role needs and denying the rest by resource type, compartment and interaction. Narrowing limits what a search returns, but the authorization rules decide whether a request can proceed at all, so the two must agree. Keep the rules short enough that a reviewer can read them against the access policy. Done means each rule has a named owner in your access documentation and a matching test case.
Confirm out-of-scope searches return nothing
Run a set of test requests as each test user, using the request patterns your applications actually send: a patient-scoped search, a search by identifier, an include, a history read and a conditional update. For a patient outside the user's list, a search should return no results, and a direct read should be refused. Record each request, the expected result and the actual result. Done means every out-of-scope request produces the expected empty or denied result, and any mismatch is fixed and retested.
Confirm conditional updates outside scope are rejected
Send conditional create, update and delete requests that target a patient outside the user's permitted list, and confirm the server rejects each one with an authorization failure and writes no change. Also confirm that the same operation against a permitted patient succeeds. Include a case where a request tries to change the patient reference on a resource already in scope. Done means the rejected requests leave the data unchanged in the database, and the record of each attempt is available for your audit process, which is covered in the sibling audit topic.
How narrowing pairs with authorization in different environments
In a single-tenant hospital deployment, one HAPI FHIR server serves one organization's clinicians and patients. Authorization rules decide which resource types and operations a user may call at all, while the SearchNarrowingInterceptor limits what a permitted search can return to the patients that user may see. The two layers answer different questions, so the design normally needs both.
- Authorization first: Define AuthorizationInterceptor rules by resource type, compartment and operation so that users without the right role cannot reach an endpoint.
- Compartment narrowing: Restrict searches to the Patient compartment or to the patients on the user's care team, based on claims supplied by your identity provider.
- Value set scoping: Where access depends on classification, such as department or sensitivity, scope searches by value set and confirm the value set content matches your written policy.
- Identity mapping outside HAPI FHIR: Your identity provider and care-team source must supply each user's patient relationships. HAPI FHIR enforces the decision but does not decide who is on a care team.
- Emergency access and audit: Plan break-glass procedures and make sure denied requests and narrowed searches appear in your audit records.
Confirm with your team that every search path your clients use is covered by a test, using a user who should see only some patients.
With JPA partitioning, each resource is placed in a partition, which can separate tenants, data sources or regions. Narrowing and authorization must then respect partition boundaries as well as patient compartments. Partitioning is a data placement feature, so it does not by itself prevent a user in one tenant from reading another tenant's data. Your rules have to enforce that boundary.
- Partition as a boundary: Map each tenant to its partition and derive the tenant from trusted token claims only, never from a request parameter the caller can change.
- Narrowing inside each partition: Compartment and value set narrowing still apply within a partition, so a clinician sees only permitted patients in their own tenant.
- Partition routing: Document how each request reaches its partition in your configuration, and test that a token issued for tenant A cannot select tenant B.
- Cross-tenant identities: Regional auditors and shared service accounts need explicit rules and their own identities. Document each one and review them on a schedule.
- Privileged partition operations: Partition management and reindexing are administrative actions, so restrict them as part of your administrative lockdown.
Verify with negative tests that use each tenant identity against resources in every other partition, and keep the results with your change records.
When a third-party app reads data for a clinician, the server receives the app's token, and the access it grants depends on the clinician's patient context and the scopes the app was granted. Both come from the authorization server, not from the app's own claims. HAPI FHIR provides the enforcement points, but the SMART on FHIR authorization flow, token validation and consent handling must be designed around them.
- Scope to rule mapping: Translate granted scopes into AuthorizationInterceptor rules so an app can read only the resource types its scopes cover.
- Patient context: Carry the launch patient from the authorization server into the narrowing logic, and reject requests that try to search outside that context.
- Token validation: Validate issuer, audience and expiry before authorization rules run, using your identity provider settings, either in an interceptor or at the gateway.
- Consent handling: Confirm how consent decisions combine with narrowing in your build, since they are a separate mechanism that your policy may require.
- App registration controls: Control which apps are registered, which scopes each may request and how access is revoked, usually in the identity provider and API gateway.
Test with a registered app acting for two clinicians with different patient lists, and confirm that each session returns only that clinician's patients.
How a search request flows through identity, narrowing and authorization
The request starts at the client app, passes the reverse proxy, and is checked by the external identity provider before it reaches the HAPI FHIR JPA server. Inside the server, the AuthorizationInterceptor decides whether the search may run at all, and the SearchNarrowingInterceptor then adds the user's permitted patient set to the query. The database only ever sees the narrowed search. Check that denied requests return before any database query runs, and that the patient set is built from the token's identity, not from client input.
Search path from client through identity, authorization and narrowing to the database.
Security risks when narrowing searches
Search narrowing only protects data on the paths it covers, so each risk below is a gap between what the interceptor scopes and what the server can still return. Read the cards as a checklist: confirm every search path, conditional operation and audit trail is covered by the same rules before you rely on patient scoping.
Narrowing applied to some search paths
The SearchNarrowingInterceptor scopes the searches it sees, so a resource type, operation or custom endpoint that bypasses it can return patients the user should not reach. Test each resource type your clients use with a restricted account, including _include, _revinclude and paging links. Pair the narrowing with deny-by-default rules from the AuthorizationInterceptor, so an unscoped request fails instead of returning everything.
Bypass through conditional operations
Conditional create, update and delete select target resources by search criteria, so a write can touch records outside the user's patients if the criteria are not narrowed the same way as a read. Check that conditional URLs are evaluated under the same compartment and value set limits, and that a conditional update cannot create a resource for a patient the user is not permitted to access. Write explicit test cases for each conditional interaction you allow.
Bypass through chained searches
Chained parameters and reverse includes can reach resources through a patient reference that is not itself in the user's list, such as an observation that points to a restricted patient. Confirm the narrowing applies to the final result set and to each linked resource, not only to the top-level resource type. Include chained queries such as Observation searches that filter on subject attributes in your test matrix.
Stale patient lists
If the user's permitted patients are cached in a token claim or a lookup table, a care team change or consent revocation may not take effect until the cache expires. Decide how long a patient list may remain valid, where it is refreshed from, and what happens when the source is unavailable. Ask your identity and EHR owners to confirm the refresh path and the time window for revocation.
Token validation gaps
Narrowing depends on knowing who the caller is, so an interceptor that trusts an unverified token, a missing audience check or an expired token can grant the wrong patient list. Validate signature, issuer, audience, expiry and the patient or scope claims in every request path, and reject requests that carry no token rather than falling back to anonymous access. Confirm the validation logic against your identity provider's current signing keys.
Missing audit of denied queries
A search that returns fewer results because of narrowing, or is rejected outright, leaves no trace unless you log it. Without records of denied and narrowed queries, you cannot show that unauthorized access was attempted or detect a misconfigured client. Route denials and narrowing decisions into your audit pipeline with the user, client, query and outcome, following the design in the audit logging topic.
Administrative paths around the rules
Reindex, expunge, partition management and package install operations can change or reveal data without passing through patient narrowing. Restrict these operations to a separate administrative identity, disable interactions your deployment does not use, and confirm that no admin endpoint is reachable from the client network. The locking down administrative operations topic covers the control set in detail.
Questions teams ask before narrowing searches in HAPI FHIR
What drives the cost of narrowing searches to a user's patients in HAPI FHIR?
The cost follows the number of resource types, compartments and access paths that must be scoped, plus how many user roles and patient relationships the server has to honor. Narrowing is one piece of a wider authorization design, so the work usually includes deciding which users may see which patients, writing the rules, and testing them against real request patterns. Ask a partner for a written scope that lists the resource types in use, the search and conditional operations clients call, the identity source that supplies the patient relationship, and the test cases that will prove coverage. Ongoing costs come from maintaining rules as the data model and client apps change.
How long does it take to implement search narrowing in HAPI FHIR?
Duration depends on how many compartments and value sets must be scoped and how settled the identity and patient-linking model already is. A team with an existing HAPI FHIR JPA server and a clear patient relationship model can usually move faster than one still deciding who owns which patients. No duration is set in this page's research, so ask any partner for a timeline tied to a written scope with named milestones, and confirm which parts depend on your identity provider or on decisions your clinical and compliance owners still need to make.
What does the client's team need to provide for this work?
The work needs people who know the data model and the access policy, not only the server. Typically this includes an owner for the patient-to-user relationship rules, engineers who can run the HAPI FHIR JPA server and its Java build, and someone who can supply test accounts and realistic request logs from client applications. Identity administrators must confirm how roles and attributes arrive in tokens. Ask a partner to list these inputs in the written scope so that dependencies are visible before work starts.
Can an internal team implement search narrowing without outside help?
Yes, a capable internal team can implement it, provided it has Java and HAPI FHIR experience and a clear authorization policy written down before coding begins. The hard part is rarely the interceptor configuration; it is deciding which searches must be narrowed, closing gaps where clients can bypass a narrowed path, and proving the result. Teams that lack security testing experience often choose a partner for the review and testing stage even when they build the rules themselves. Your own assessment should weigh the staff time available against this risk.
How do I test that search narrowing covers every path to patient data?
Start by listing every search parameter, chained search, _include and _revinclude path, and conditional operation that clients use, then check each one against accounts with different permissions. Test that users receive only resources in their permitted compartments and value sets, and that requests outside those sets return nothing or an error as designed. Include direct reads by ID, history and bulk export, because narrowing on search alone does not cover them. Keep the test cases in version control so they run after every upgrade or rule change. Ask a partner whether security testing of the API is part of the written scope, since DeployOpen runs application and API security testing.
How do upgrades of HAPI FHIR affect the search narrowing interceptors?
Upgrades can change interceptor behavior, supported Java versions and the database schema, so narrowing rules need a regression run after every upgrade. HAPI FHIR 8.2.0 requires JDK 17, and the latest release noted in the research is v8.8.2, released on 25 September 2026. Check the version-by-version upgrade notes and the release page before moving, then rerun your full narrowing test suite against the new build in a non-production environment. Ask any partner to include upgrade testing and rule review as a recurring item in the scope or retainer.
Does search narrowing alone satisfy our access control requirements?
No. HAPI FHIR states that it does not provide a single security layer and offers building blocks, so search narrowing works best alongside authentication, the AuthorizationInterceptor rules, consent handling and audit logging. Narrowing controls what a search returns, but it does not establish who the user is or record what they accessed. Ask a partner to show how these controls fit together in the written scope and which evidence your compliance team will need from each one.
Limits to confirm in your environment
Search narrowing only protects data for the searches and operations it actually covers, in the exact versions and database you run. The cards below list the checks to make against the HAPI FHIR documentation and your own test results before any user's patient list is treated as enforced.
Covered parameters and operations
Confirm which search parameters, compartments and operations the SearchNarrowingInterceptor narrows in the HAPI FHIR version you deploy. Check reads, searches, chained searches, _include and _revinclude, and conditional create, update and delete separately, because coverage is not guaranteed to be identical across them. Record the result as a matrix of request patterns your applications really send, and treat any uncovered pattern as a gap to close with an authorization rule or a deny.
Security docsJDK 17 and version alignment
HAPI FHIR 8.2.0 requires JDK 17, so confirm the JDK your application server runs and the HAPI FHIR release your build pulls. Mismatched versions in the server and in any custom interceptor can change how narrowing is applied. Pin the exact versions in your build, rerun the narrowing tests after every upgrade, and check the release notes for changes to interceptor behavior.
Versions pageDatabase behavior under PostgreSQL or SQL Server
Narrowing generates queries that run against the database you choose, so test the same scenarios on PostgreSQL or Microsoft SQL Server, not only on the embedded H2 default. Confirm that filtered searches return the same results, that paging and total counts remain correct, and that no query falls back to a scan that exposes data or stalls. Note that the starter does not support MySQL.
Starter repositoryInteraction with partitioning
If you use JPA partitioning for multitenancy, regional grouping or separate data sources, verify that narrowing respects the partition a request resolves to. A user scoped to one patient set in one partition must not see matching resources in another partition through a search or an include. Test cross-partition requests explicitly, and confirm how the partition is selected for each client, since a wrong tenant header can bypass the intended boundary.
Partitioning docsPerformance on large datasets
Narrowing adds criteria to searches, which can change query plans and response times on large patient populations. Benchmark representative user profiles with the largest compartments you expect, and compare response times and database load with narrowing on and off. Check whether value set expansion used for narrowing is cached or recomputed per request, and set limits and indexes based on measured results rather than assumptions.
Pairing with authorization rules
Narrowing limits what a search returns but does not decide whether a request is allowed at all. Confirm that the AuthorizationInterceptor rules deny the operations you do not intend to support, so that an unnarrowed path cannot be used to reach the same data. Test each rule with a user who holds no patients, a user with one patient, and a user with many, and record the outcomes as evidence for your access review.
How DeployOpen scopes and delivers search narrowing for HAPI FHIR
DeployOpen starts every search narrowing engagement with a written, fixed scope agreed before any configuration begins. The scope names the resource types, compartments and value sets that narrowing will cover, the operations in scope (searches, conditional reads, conditional updates and conditional deletes), the identity provider and authorization rules the work must integrate with, and the environments where it will run. Because the permission model is the part most likely to be wrong, DeployOpen designs it with your security and compliance teams before implementation. Expect to decide together which user attributes map to patient compartments, how care relationships are represented, what happens to searches that do not specify a patient, and who approves changes to the rules later. Those decisions are written down as the acceptance baseline for the work.
Implementation runs on infrastructure you control, including your cloud accounts, data centers or air-gapped networks, so the narrowing interceptor, its configuration and the test environment sit inside your change process. DeployOpen builds test cases from real request patterns captured from your applications, including chained searches, _include parameters, paging links and bundle requests, because narrowing that works for a simple patient search can still leak data through a secondary query. Each test is tied to a permitted or denied user profile, and failing cases are fixed and retested before handover. DeployOpen prepares the test results, configuration records and change history as evidence for your internal reviews and assessments. It does not issue audit reports, attestations or certifications; independent auditors and certification bodies do that work.
After handover, a retainer can cover upgrades of HAPI FHIR and the JPA server, retesting when rules change, and review of new request patterns from applications. Pricing is not published, and a quote follows from the written scope, so ask for the scope items, the environments covered, the test case count and the retainer terms to be itemized. Confirm with your own engineers which HAPI FHIR version and JDK your environment requires before the quote is finalized, since those details shape the effort.

