Securing Spring Boot applications with Keycloak

Protect Spring Boot web apps and REST APIs with Keycloak through Spring Security's OAuth 2.0 client and resource server support, replacing the deprecated Keycloak adapter. This page covers the setup sequence, role mapping, security settings and testing.

On this page

Why Spring Boot teams are moving off the Keycloak adapter

If your Java team runs Spring Boot web apps or REST APIs that need Keycloak sign-in, the first decision is which integration path to build on. Many existing services still use the Keycloak adapter, which is deprecated, and the supported route is Spring Security's OAuth 2.0 support: the OAuth 2.0 client for browser login and the resource server for bearer tokens. Both are configured against the issuer URI of your Keycloak realm, so Spring Security reads the realm's discovery document and picks up its endpoints and signing keys itself. Before you migrate, inventory every service that depends on the adapter, the keycloak.json or Spring adapter properties each one uses, and the versions of Spring Boot and Spring Security they run. Confirm the exact versions you need with the Spring project's own documentation rather than assuming a version works.

This page covers three things that decide whether the migration holds. The first is issuer discovery: the issuer string in your configuration must match the iss claim Keycloak puts in tokens, including the hostname as clients see it, so a mismatch between an internal and a public hostname is a common cause of failed startup or token rejection. The second is role-to-authority mapping: Keycloak places realm and client roles in token claims that Spring Security does not read as GrantedAuthority values by default, so you will need a converter that maps those claims to the ROLE_ authorities your hasRole and method security rules expect. The third is testing, covering login redirects, token validation failures and authorization rules, which should run before any cutover. Each of these is covered in the sections that follow.

What a Spring Boot Keycloak integration needs before the build

Most Spring Boot integration problems trace back to decisions made before any code is written: which realm and issuer the app trusts, whether the client holds a secret, and whether the app can reach Keycloak at all. The cards below cover what to settle and confirm first, so the build starts from a stable target.

Realm and public issuer URL

The application validates tokens against one issuer string, and that string must match the iss claim Keycloak puts in each token. Decide which realm the app will use and confirm the hostname clients see, served over TLS. If the app reaches Keycloak through an internal address but tokens carry the public hostname, validation fails. Check the frontend URL settings before you write any configuration.

Production guide

Network path to the discovery endpoint

Spring Security reads the realm's OpenID configuration at startup or on first use to find the JWKS keys and token endpoints. Confirm that the application host can reach the issuer's /.well-known/openid-configuration document, including through egress proxies, private DNS and certificate trust stores used by your Java runtime. A discovery failure often looks like a startup error unrelated to Keycloak, so test this path directly first.

Confidential or public client decision

A server-rendered Spring Boot web app that signs users in should normally be a confidential client that holds a client secret and uses the authorization code flow. A browser-based SPA or native app cannot keep a secret and needs a public client with PKCE. A pure REST API usually needs no login client at all, only a resource server that validates bearer tokens. Record which role each application plays before you create its client in Keycloak.

Spring Boot and Java versions

Spring Security's OAuth 2.0 client and resource server modules depend on the Spring Boot and Java versions in your build. Confirm the versions you target against the Spring Security reference documentation, including its supported Java baseline and any changes to OIDC defaults. Pin them in your build file so that a dependency update does not silently change token validation behavior.

Keycloak version and release notes

Confirm the Keycloak version your environment runs against the current release notes before you copy client settings or property names from examples. Minor releases can include breaking changes, and some upgrade notes change default behavior that affects sign-in or logout. Your team should own this check because the Spring Boot code works against the Keycloak server's current behavior, not against a version you assumed.

Upgrade guide

Roles, claims and ownership of the build

Decide early which Keycloak realm roles, client roles or groups become Spring authorities, because Keycloak places them in token claims that Spring does not read by default. Name who owns the Keycloak client configuration, who owns the application configuration, and how changes are reviewed. Without that split, role mapping and redirect URI changes tend to be made in two places and drift apart.

How to configure the Spring Boot and Keycloak integration in order

This sequence takes a Spring Boot application from a blank Keycloak realm to a working sign-in and token check, with each step closed by a verifiable result. Follow it in order, because later steps depend on the issuer, client and role settings created earlier.

  1. Create the realm and confidential client

    In the Keycloak admin console, create a realm for the application (or select an existing one) and add a client for the Spring Boot web app. Set client authentication on so the app holds a client secret, and enable the standard authorization code flow. For a resource server that only validates bearer tokens from other clients, you may not need a browser client at all, so confirm which role the application plays before you create it. The step is done when the client appears in the realm with its client ID and secret stored in your secrets manager, not in source control.

  2. Set redirect URIs and web origins

    Add the exact callback URL your Spring app uses after login, which by default follows the pattern of the application base URL plus /login/oauth2/code/ and the registration ID. Add the post-logout redirect URI if the app supports logout. Set web origins only for browser clients that call Keycloak from JavaScript, and avoid wildcards in production. Confirm the callback URL matches the public hostname behind your reverse proxy, since a mismatch is one of the most common causes of login failures. The step is closed when a test login reaches the callback without a redirect URI error from Keycloak.

  3. Confirm the issuer URI and discovery document

    Determine the issuer URI for the realm, which takes the form of the Keycloak base URL followed by the realms path and the realm name. Open the realm's OpenID configuration discovery document in a browser or with curl and confirm it loads over HTTPS and lists the authorization, token, userinfo and JWKS endpoints. Check that the issuer value in the document matches the URI you plan to configure exactly, including scheme, hostname and trailing path. Spring uses this document at startup to find endpoints and signing keys, so the step is done when the document loads and the issuer values match.

  4. Add the Spring dependency for the chosen role

    In the build file, add the Spring Security OAuth 2.0 client starter if the application signs users in through a browser, or the OAuth 2.0 resource server starter if it only accepts bearer tokens in REST API requests. Many applications need both, in which case add both and configure each filter chain separately. Keep the Spring Boot and Spring Security versions on a line your team has confirmed is supported. The step is closed when the project builds and the dependency tree shows the expected starter, with no leftover Keycloak adapter dependency.

  5. Set the issuer URI and client properties

    Add the issuer URI to the application configuration under the resource server or OAuth 2.0 client provider settings, and add the client ID, client secret and scope properties for the browser login registration. Load the client secret from an environment variable or secrets store rather than a committed file. Start the application and watch the log for errors during discovery, since Spring fetches the discovery document and JWKS during startup and fails fast if they are unreachable. The step is done when the application starts cleanly and logs no discovery or JWKS errors.

  6. Map Keycloak roles to Spring authorities

    Keycloak places realm and client roles in claims in the access token, not in the standard scope claim Spring reads by default. Write a converter or customize the JWT authentication converter so the roles claims become GrantedAuthority values with the prefix your authorization rules expect. Decide which claim holds the roles for each client, then add a test user with a known role. The step is closed when an authorization rule that requires that role allows the request and a request without it is denied.

  7. Verify login and token acceptance

    Sign in through the browser with a test user and confirm the session reaches the protected page. Then call a protected REST endpoint with a bearer token obtained for that user, and confirm the request is accepted. Send a request with an expired, altered or wrongly issued token and confirm it is rejected with an unauthorized response. Keep a short checklist of these cases so the same tests run again after each Spring Boot, Spring Security or Keycloak upgrade. The step is closed when both valid and invalid cases behave as expected.

How a browser login and an API bearer token flow through Keycloak and Spring

The browser starts at the Spring Boot web app, which redirects the user to Keycloak for an authorization code login and receives tokens on the back channel. The API flow starts with a client that presents a bearer token to the resource server, which checks its signature against the issuer's published keys before serving the request. Check that the public side only reaches Keycloak's login endpoints and the app's public routes, and that the internal app network holds no path that skips token validation.

Browser login through the web app, and API calls validated by the resource server.

Choosing how to map Keycloak roles to Spring authorities

Realm roles are shared across every client in a realm, so they suit applications that need one common vocabulary such as user, auditor or admin. Keycloak adds them to the access token under the realm_access claim as a roles array when the default roles mapper is in place. Your Spring converter reads that array and turns each entry into an authority. The approach is simple to explain to auditors, but it couples every application in the realm to the same role names, so a change for one app can affect others.

  • Default claim name: Keycloak emits realm roles under realm_access.roles in the access token.
  • Shared meaning: A role such as admin means the same thing to every client in the realm, which helps governance but limits per-app nuance.
  • Composite roles: Realm roles can contain other roles, so the token may carry expanded role names your converter must expect.
  • Blast radius: Renaming or reassigning a realm role changes access in every application that reads it.
  • Default roles: Keycloak's default-roles composite is added to new users, so confirm it does not grant more than your apps expect.

Before you rely on this claim, check the client scope and the mapper configuration in Keycloak that carries realm_access into the token for each client your API accepts.

Mapping Keycloak claims to Spring Security authorities

This table compares each Keycloak token claim with where it appears, the Spring authority it usually becomes, and who should own the decision to map it. Read it before writing a JwtAuthenticationConverter, then confirm each field in your own realm because Keycloak's default mappers and client scopes vary by configuration. The main takeaway is that subject and email identify users, while authorities should come only from claims your security team has approved.

Claim or sourceWhere it appears in the tokenSpring authority it becomesWho owns the mapping decision
Subject (sub)Top-level claim in the access token and ID tokenNot mapped to an authority; used as the principal nameApplication team, with the identity team confirming the ID is stable
Preferred username (preferred_username)Top-level claim, added by the default profile mapperNot mapped to an authority; often used for display or audit logsApplication team; confirm the mapper is enabled on the client scope
Email (email)Top-level claim, present only when the email scope is requested and the user has an emailNot mapped to an authority; avoid using it for access decisionsIdentity team; confirm email verification status in your realm
Realm roles (realm_access.roles)Nested object realm_access, list of role namesROLE_ prefixed authorities, once the converter reads this pathSecurity team approves which realm roles grant access; application team writes the converter
Client roles (resource_access.<client>.roles)Nested object keyed by client ID, each with a roles listROLE_ prefixed authorities, only for the API client ID you choose to readApplication team for its own client; identity team for role assignment
Groups (groups)Top-level list, present only when a group membership mapper is added to the client scopeAuthorities from group paths, if the converter maps them; often ROLE_ or a custom prefixIdentity team configures the mapper; security team decides which groups grant access

Security settings that protect the Spring integration

A Spring Boot application trusts Keycloak only as far as its configuration allows, so the settings below decide who can sign in, which tokens are accepted and where credentials live. Each card names a setting to confirm against the current Spring Security and Keycloak documentation before the integration goes to production.

TLS on every hop

Tokens, authorization codes and client credentials cross several connections: browser to Keycloak, browser to the Spring app, Spring app to Keycloak's token and JWK endpoints, and Keycloak to its database. Serve every one of them over TLS. Keycloak's production guide calls for TLS on all communication, and the Spring side needs the issuer URI to use https so that discovery and token validation trust the same endpoints. Confirm the certificate chain is trusted by the JVM running the app, including any internal certificate authority.

Keycloak production guide

Validating issuer and audience

Accepting a JWT because its signature checks out is not enough. Set spring.security.oauth2.resourceserver.jwt.issuer-uri to the exact issuer of your realm so that discovery and the iss claim match, and add an audience validator so that tokens issued for another client are rejected. Keycloak's aud values depend on client scopes and audience mappers, so confirm which audience your API receives before relying on the check.

Redirect URI and web origin restrictions

In the Keycloak client, the valid redirect URIs and web origins define where an authorization code or token can be delivered. Use exact URLs for the Spring login callback, such as the default /login/oauth2/code/{registrationId} path, and avoid wildcards that match other paths or subdomains. Keep post-logout redirect URIs as narrow as the application allows. Confirm each entry against the current Keycloak client settings and the Spring registration ID you chose.

Client secrets kept out of source control

A confidential client secret or private key should never appear in a repository, image layer or application.yml committed to version control. Supply spring.security.oauth2.client.registration.*.client-secret through environment variables, a mounted secret or a secrets manager your platform uses. Rotate the secret in Keycloak when people with access change, and confirm how your deployment tooling masks the value in logs and startup output.

CSRF behavior for session-based apps

Spring Security enables CSRF protection by default for state-changing requests, which matters for server-rendered apps that keep the user's session after Keycloak login. Do not disable it to fix a failing form or a logout call without understanding why it fails. Confirm how your frontend sends the CSRF token, and check whether any REST endpoints you expose to browsers use cookies, since bearer-token APIs often make different choices.

Separating the admin console from public URLs

Keycloak's production guide recommends exposing the admin console and Administration REST API on a different hostname or context path from public frontend URLs. Point the Spring application at the public frontend issuer only, and keep administrative endpoints off the reverse proxy routes your application users reach. Confirm the hostname and admin settings in your Keycloak configuration, and test that the admin paths are unreachable from the public network.

Keycloak production guide

How to test login, authorities and token rejection before release

Testing for this Spring Boot integration needs three layers, and each one catches a different failure. Unit tests for the authority converter come first: feed the converter hand-built JWTs that mimic the realm_access.roles and resource_access claims your realm produces, then assert the exact GrantedAuthority values, including the ROLE_ prefix your hasRole and hasAuthority rules expect. Slice or integration tests come second. Spring's test support can build a Jwt directly through the jwt() request post-processor in MockMvc, which is fast and exercises your SecurityFilterChain, but it skips the real signature and issuer checks. For that, run a Keycloak container with a seeded realm (a JSON realm export committed to the repository works well) and point spring.security.oauth2.resourceserver.jwt.issuer-uri at it, so the decoder performs genuine discovery and key retrieval.

Negative tests matter as much as the happy path. Write explicit cases for an expired token, a token whose aud does not include your API's audience, a token signed by a different realm, and a valid token that lacks the role an endpoint requires. Each should assert a 401 or 403 with no body leakage. Keep the issuer configuration identical across environments: the same issuer-uri format and the same realm name, not a test-only shortcut such as a static jwk-set-uri pointing at a file. If the test path and the production path validate tokens differently, the tests prove little. Confirm with your platform team which hostname the issuer advertises, because a mismatch between the internal and public frontend URL will fail discovery in one environment and pass in another.

Role changes in Keycloak need a regression check every time, not only when code changes. A client role renamed, a composite role edited, or a mapper altered in the admin console can silently remove authorities that the seeded realm still grants. Schedule the integration suite against the realm export that is actually deployed, or diff the exported realm from each environment against the committed one before a release. Ask your security team to confirm which roles grant administrative endpoints, and make sure those paths have a negative test that proves a non-admin token is refused.

Common failures when Spring Boot meets Keycloak

This table pairs the failures teams most often hit when wiring Spring Boot to a Keycloak realm with their likely configuration cause and the fix. Read it by symptom first, then check the cause against your issuer URI, client settings and resource server properties. Most failures trace back to a mismatch between what Keycloak issues and what Spring Security expects.

SymptomLikely causeFix
Startup or token validation fails with an issuer mismatchThe configured issuer URI does not match the iss claim in the token, often because the Keycloak hostname, port or realm name differs between the app and the token sourceSet the issuer URI to the exact frontend URL Keycloak advertises for the realm, and confirm it matches the iss claim in a decoded test token
Login redirects fail with a redirect URI rejected by KeycloakThe redirect URI registered on the Keycloak client does not match the URI Spring Security sends, including scheme, host, port, path or a trailing slash behind a reverse proxyRegister the exact callback URL on the client, and make sure forwarded headers reach Spring Boot so it builds the same scheme and host
Users sign in but have no authorities or get access deniedKeycloak roles are nested in the token (for example under realm_access or resource_access) and are not converted into Spring Security GrantedAuthority values, or the role prefix expected by hasRole differsAdd a JwtAuthenticationConverter or a custom mapper that reads the Keycloak claims and maps each role to an authority with the prefix your rules use
API returns 401 for a valid-looking tokenThe access token audience (aud) does not include the resource server's client or audience value, so the resource server rejects itAdd an audience mapper to the client that issues the token, or add an audience validator in the resource server with the expected value
Tokens intermittently rejected as not yet valid or expiredClock skew between the Keycloak host, the Spring Boot host and any proxy, which shifts the iat, nbf or exp checks outside the allowed toleranceSynchronize all hosts with NTP, and keep the validator's clock tolerance at the default unless your environment has a documented reason to change it
Application starts but ignores expected settings or loads an old login flowLeftover keycloak.* properties or the deprecated Keycloak adapter dependency are still on the classpath, so old configuration is read alongside the spring.security.oauth2 settingsRemove the adapter dependency and all keycloak.* keys, keep only spring.security.oauth2 client and resource server properties, and confirm the active configuration at startup
Resource server cannot fetch signing keys after a realm key changeThe JWK set cached by the resource server is stale, or the jwk-set-uri or issuer-uri points to a different realm than the one that issued the tokenConfirm the realm in the issuer or JWK set URI, and let the decoder refresh keys on an unknown key ID rather than restarting the service
Logout or callback errors after the app is moved behind a proxyProxy path rewriting or missing forwarded headers change the URLs Spring Boot generates for the callback and post-logout redirectEnable forwarded header handling in Spring Boot, and register the public post-logout and callback URLs on the Keycloak client

What teams ask before they move a Spring Boot app to Keycloak

How much effort does moving a Spring Boot app to Keycloak take?

The effort depends less on the Spring code than on what the app depends on today. Most of the work is in the login and token path: replacing the adapter configuration with spring-boot-starter-oauth2-client for web apps or spring-boot-starter-oauth2-resource-server for APIs, registering clients in Keycloak, and mapping roles. The main drivers are the number of endpoints with custom security rules, how much the app reads from the old adapter's classes, whether sessions or stateless tokens are used, and how many environments must be verified. Ask any partner to list those drivers against your codebase before agreeing a plan, since they determine the scope rather than a generic estimate.

Can our own team migrate Spring Boot apps to Keycloak without outside help?

Yes, a team with Spring Security experience and access to a Keycloak realm can do the work in-house, and the Spring Security documentation covers the OAuth 2.0 client and resource server modules directly. The questions to answer honestly are whether anyone has tested token validation, logout and role mapping end to end, and whether the team will own Keycloak client settings after go-live. Outside help is most useful for a fixed set of apps that must move together, for security review of the result, or for knowledge transfer so the in-house team can run it afterward.

What does the migration need from our side?

Three roles must be named before work starts. A realm owner decides realm layout, client policies, token lifetimes and who may change Keycloak configuration. App owners confirm which endpoints, roles and user attributes each application relies on and sign off on behavior. A test environment with a running Keycloak realm, test users with representative roles, and a way to call each API with real tokens is needed to verify results. Access to source repositories, CI pipelines and the deployment target should also be arranged early, because delays in those usually set the schedule more than the code changes do.

How does the number of apps and the role model affect cost?

Cost grows with the number of distinct applications and clients, because each one needs its own client registration, redirect URIs, scopes and tests. The role model is the second driver. A small set of realm roles mapped to authorities is simple, while client roles, composite roles, group-based access and per-tenant claims each add mapping logic and test cases. Shared libraries across services reduce repeated work, and apps that use custom filters or method security annotations take longer to review. Ask for the quote to list each app, its roles and its test cases separately so the drivers are visible.

Do we have to remove the Keycloak adapter before we start?

You do not have to remove it all at once, but the adapter is deprecated, so the target should be the Spring Security OAuth 2.0 modules. A common approach is to build the new configuration in a branch or separate module, run both paths in test, and switch each application after its tests pass. Watch for code that imports adapter classes directly, such as token or security context types, because those references must be replaced with Spring Security equivalents. Keep the old adapter dependency until no code path uses it, then remove it and its configuration keys in the same change.

How should we scope the work in a written fixed-scope agreement?

A fixed-scope agreement works best when the scope lists the applications, the authentication patterns each one uses (browser login, bearer-token API or both), the Keycloak client settings to be created, the role mappings in scope, the test cases and environments, and the handover items such as configuration notes and runbooks. It should also state what is excluded, such as frontend changes, Keycloak server upgrades or custom user federation. Deliverables and acceptance checks should be written down, and any change to the list of apps should go through a documented change request. Written scope makes the quote traceable to the work rather than to hours.

What breaks most often when Spring Boot apps move to Keycloak?

The most common failures are issuer mismatches, where the issuer-uri does not match the hostname tokens are issued under, often because of a reverse proxy. Role mapping is the second, since Keycloak places roles in claims that Spring does not read as authorities by default, so a converter is needed. Redirect URI mismatches, missing audience checks and sessions that behave differently behind a load balancer also cause trouble. Include tests that call protected endpoints with tokens from each role, and check logout and expired token behavior before go-live.

How DeployOpen scopes and delivers a Spring Boot Keycloak integration

DeployOpen plans, builds, tests and documents Spring Boot integrations with Keycloak inside the client's own infrastructure. Each engagement starts from a written scope that names the applications, realms, clients and roles involved, so the work can be checked against what was agreed.

How we scope

  • Inventory each Spring Boot web app and REST API, noting whether it serves browser users, machine clients or both.
  • Agree in writing which realm, clients, redirect URIs and role model the integration will use before build starts.
  • Confirm the Keycloak version, hostnames and TLS setup in your environment, since issuer URLs must match exactly across services.

How we build

  • Configure Spring Security's OAuth 2.0 client for browser login and resource server support for bearer tokens, without the deprecated adapter.
  • Map Keycloak realm and client roles to Spring authorities in code that your developers can read and extend.
  • Write automated tests for authenticated, anonymous and wrong-role requests, and run them against a Keycloak instance in a test environment.

How we hand over

  • Deliver the source, client configuration notes, and a record of every setting that differs between environments.
  • Document how to rotate client secrets, change issuer settings and add a new role, so your team can make those changes alone.
  • Walk your developers and operators through the tests and the runbook, and agree which items remain with your team after handover.

How we support

  • Engagements are fixed-scope, and the written scope defines the deliverables and the timeline before work begins.
  • Ongoing support, Spring Boot or Keycloak upgrades and continuous security testing are available as retainers.
  • Ask any partner for a quote built from the written scope, and confirm who maintains the application code after the engagement ends.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.