Add Keycloak login to a Spring Boot app
Sign users in to a Spring Boot 4 app with Keycloak through Spring Security's OAuth2 client, protect a JWT API with realm roles, and log out of Keycloak.
A Spring Boot web app signs users in with the authorization code flow through Spring Security's OAuth2 client, and a separate Spring Boot API checks Keycloak access tokens as a resource server and maps realm roles to authorities.
Written against Spring Boot 4.2.0 (the current release), Spring Security 7.2.0, Java 21 and Keycloak 26.8, checked on 25 November 2026. Spring Boot 4 renamed the starters to spring-boot-starter-security-oauth2-client and spring-boot-starter-security-oauth2-resource-server; the old names spring-boot-starter-oauth2-client and spring-boot-starter-oauth2-resource-server still work in 4.2 but are deprecated.
Replace auth.example.com with your RealmDeploy hostname and acme with your realm.
Create the client in Keycloak
Open Clients, choose Create client, and use these values:
| Setting | Value |
|---|---|
| Client type | OpenID Connect |
| Client ID | spring-app |
| Client authentication | On |
| Authentication flow | Standard flow. Turn Direct access grants off. |
| Root URL | http://localhost:8080 |
| Valid redirect URIs | http://localhost:8080/login/oauth2/code/keycloak |
| Valid post logout redirect URIs | http://localhost:8080 |
| Web origins | Leave empty. The browser never calls Keycloak from JavaScript. |
Choose Save, then copy the secret from the Credentials tab.
The redirect URI is Spring Security's default, /login/oauth2/code/ followed by the registration ID, which is keycloak below. For production, add your app's real URLs next to the local ones, for example https://app.example.com/login/oauth2/code/keycloak and https://app.example.com. Keycloak compares redirect URIs exactly.
Environment variables
Spring Boot reads these from the environment. Set them in your shell or in your IDE's run configuration:
export KEYCLOAK_ISSUER=https://auth.example.com/realms/acme
export KEYCLOAK_CLIENT_ID=spring-app
export KEYCLOAK_CLIENT_SECRET=paste-the-client-secretInstall
Create a project with Java 17 or newer (Spring Boot 4.2 needs at least Java 17) and add the Spring MVC and OAuth2 client starters:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-oauth2-client</artifactId>
</dependency>
</dependencies>With Gradle, use the same two starters with the Spring Boot plugin 4.2.0.
Add login
Register Keycloak as an OpenID Connect provider. With issuer-uri set, Spring reads https://auth.example.com/realms/acme/.well-known/openid-configuration at startup and takes every endpoint from it:
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: ${KEYCLOAK_CLIENT_ID}
client-secret: ${KEYCLOAK_CLIENT_SECRET}
scope: openid,profile,email
provider:
keycloak:
issuer-uri: ${KEYCLOAK_ISSUER}The registration and the provider share the ID keycloak, so Spring links them without a provider line.
The security configuration turns on oauth2Login and sends logout on to Keycloak:
package com.example.demo;
import static org.springframework.security.config.Customizer.withDefaults;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http,
ClientRegistrationRepository clientRegistrationRepository) throws Exception {
OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler =
new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/").permitAll()
.anyRequest().authenticated())
.oauth2Login(withDefaults())
.logout(logout -> logout.logoutSuccessHandler(logoutSuccessHandler));
return http.build();
}
}A page that shows the user and a sign-out button:
package com.example.demo;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;
@RestController
public class HomeController {
@GetMapping("/")
public String home(@AuthenticationPrincipal OidcUser user, CsrfToken csrf) {
if (user == null) {
return "<a href=\"/oauth2/authorization/keycloak\">Sign in</a>";
}
return "<p>Signed in as " + HtmlUtils.htmlEscape(user.getPreferredUsername()) + "</p>"
+ "<form method=\"post\" action=\"/logout\">"
+ "<input type=\"hidden\" name=\"" + csrf.getParameterName()
+ "\" value=\"" + csrf.getToken() + "\">"
+ "<button>Sign out</button></form>";
}
}Add the usual @SpringBootApplication class, run ./mvnw spring-boot:run and open http://localhost:8080. /oauth2/authorization/keycloak starts the login; Spring adds state, nonce and PKCE (code_challenge with S256) to the request, exchanges the code with the client secret and validates the ID token.
Protect an API
The API is a second Spring Boot app on port 8081 that accepts Authorization: Bearer <access token> from other clients. It needs the resource server starter instead of the OAuth2 client starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
</dependency>Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to the client whose tokens call the API:
- Open Clients, choose that client, and open its Client scopes tab.
- Choose
<client-id>-dedicated. - Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
- Enter a Name, set Included Custom Audience to
orders-api, keep Add to access token on, and choose Save.
If your API is registered as a client in the realm, pick it under Included Client Audience instead and use its client ID as the audience.
spring.security.oauth2.resourceserver.jwt.audiences exists in Spring Boot 4.2. With it and issuer-uri, Spring checks the signature against the realm's keys from /protocol/openid-connect/certs, the expiry, the issuer and the audience:
server:
port: 8081
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: ${KEYCLOAK_ISSUER}
audiences:
- orders-apiKeycloak puts realm roles in the realm_access.roles claim, which Spring does not read by default. A small JwtAuthenticationConverter turns each role into a ROLE_<role> authority, so hasRole("admin") works:
package com.example.api;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class ApiSecurityConfig {
@Bean
SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/admin/**").hasRole("admin")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(keycloakRealmRoles())))
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
// Turns Keycloak's realm_access.roles claim into ROLE_<role> authorities.
private JwtAuthenticationConverter keycloakRealmRoles() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setPrincipalClaimName("preferred_username");
converter.setJwtGrantedAuthoritiesConverter(ApiSecurityConfig::realmRoles);
return converter;
}
private static Collection<GrantedAuthority> realmRoles(Jwt jwt) {
Map<String, Object> realmAccess = jwt.getClaimAsMap("realm_access");
if (realmAccess == null || !(realmAccess.get("roles") instanceof List<?> roles)) {
return List.of();
}
return roles.stream()
.map(role -> (GrantedAuthority) new SimpleGrantedAuthority("ROLE_" + role))
.toList();
}
}package com.example.api;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@GetMapping("/api/me")
public Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
return Map.of(
"subject", jwt.getSubject(),
"username", jwt.getClaimAsString("preferred_username"));
}
@GetMapping("/api/admin/ping")
public Map<String, String> adminPing() {
return Map.of("status", "ok");
}
}A token without the orders-api audience, from another issuer, or with a bad signature gets a 401; a valid token without the admin realm role gets a 403 on /api/admin/**. The resource server fetches the realm's discovery document and keys on the first request, not at startup, and fetches the keys again when a token arrives with a key ID it has not seen. Paste a token into the JWT decoder to see its iss, aud and realm_access, or list its roles with the Keycloak token roles tool.
Log out
Spring Security's logout is a POST to /logout with the CSRF token, which the form on the home page sends. It ends the Spring session, then OidcClientInitiatedLogoutSuccessHandler sends the browser to the realm's end-session endpoint, https://auth.example.com/realms/acme/protocol/openid-connect/logout, with id_token_hint and post_logout_redirect_uri. The {baseUrl} placeholder becomes http://localhost:8080, which must be listed in Valid post logout redirect URIs. Because the ID token is sent, Keycloak ends its own session without asking. The logout URL builder shows the same URL.
This logout runs through the browser, so it needs nothing from us. If you also set a Backchannel logout URL on the client, Keycloak calls your app from your tenant, and outgoing connections from your tenant are closed by default. Tell us the host and port first through How to reach us and we open the connection.
Common errors
| Error | Cause | Fix |
|---|---|---|
Startup fails with Unable to resolve Configuration with the provided Issuer of "..." | Spring cannot load the discovery document: a typo in the hostname or realm. | Open KEYCLOAK_ISSUER plus /.well-known/openid-configuration in a browser, or use the OIDC discovery viewer. |
Startup fails with ... did not match the requested issuer ... | issuer-uri differs from the issuer in the discovery document, often by a trailing slash. | Use https://auth.example.com/realms/acme with no trailing slash. |
Keycloak shows Invalid parameter: redirect_uri | http://localhost:8080/login/oauth2/code/keycloak is not in Valid redirect URIs, or Spring builds an http:// URL behind a TLS proxy. | Add the URI exactly. Compare both with the redirect URI matcher, and see the proxy question below. |
[authorization_request_not_found] after signing in | The session cookie from the start of the login did not come back, for example because you started on 127.0.0.1 and returned to localhost. | Use one hostname throughout. |
[invalid_token_response] with unauthorized_client | The client secret is wrong, or Client authentication is off. | Copy the secret again from the Credentials tab. |
Keycloak shows Invalid redirect uri after Sign out | http://localhost:8080 is not in Valid post logout redirect URIs. | Add it exactly, without a trailing slash. |
API returns 401 with The aud claim is not valid in WWW-Authenticate | The access token has no orders-api audience. | Add the Audience mapper above and get a new token. Check it with the JWT claims validator. |
| API returns 403 for a user who has the role | The role is a client role in resource_access, not a realm role, or it is not in the token at all. | Assign a realm role, or read resource_access.<client>.roles in the converter. |
For other OAuth error codes, see the OAuth error lookup.
FAQ
Why does the signed-in user in the web app have no roles?
Keycloak's realm roles mapper, in the built-in roles client scope, adds roles to the access token only, not to the ID token that oauth2Login reads. To have them in the web app, add a User Realm Role mapper to the client's dedicated scope with Add to ID token on, then map the claim to authorities with a GrantedAuthoritiesMapper, as Spring Security's OAuth2 login documentation shows.
What changes behind a reverse proxy?
When a proxy ends TLS, Spring sees http:// and builds http:// redirect URIs. Set server.forward-headers-strategy: framework (or native when the embedded server should read the headers) so Spring uses the proxy's X-Forwarded-* headers, and make sure the proxy sends them.
Can the login app and the API be one Spring Boot app?
Yes. Keep both starters and declare two SecurityFilterChain beans: one with securityMatcher("/api/**"), @Order(1) and oauth2ResourceServer, and one for everything else with oauth2Login. We keep them apart here so each one is complete on its own.
Do I need the Keycloak Spring adapter?
No. The Keycloak adapters for Spring were deprecated years ago and are not maintained. Spring Security's own OAuth2 client and resource server are the supported way, and they need nothing Keycloak-specific beyond the converter above.
Sources
- https://docs.spring.io/spring-boot/reference/security/oauth2.html
- https://docs.spring.io/spring-boot/system-requirements.html
- https://docs.spring.io/spring-security/reference/servlet/oauth2/login/logout.html
- https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html
- https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-starter-oauth2-client/4.2.0/spring-boot-starter-oauth2-client-4.2.0.pom
- https://www.keycloak.org/docs/latest/server_admin/#audience-support
- https://www.keycloak.org/docs/latest/server_admin/#_oidc-logout
- https://openid.net/specs/openid-connect-rpinitiated-1_0.html
Add Keycloak login to a Node.js Express app
Sign users in to an Express app with Keycloak using openid-client v6 and sessions, protect API routes with jose, and log out of Keycloak.
Add Keycloak login to a Quarkus app
Sign users in to a Quarkus app with Keycloak using quarkus-oidc in web-app mode, protect a REST API with bearer tokens and realm roles, and log out.