Spring Boot and React Behind Keycloak: a Resource Server, Realm Roles and a PKCE Sign-in
Keycloak 26.4 in Docker signs the tokens, a Spring Boot API checks them, and a React app signs in with the code flow and PKCE. alice has the agent role and gets the ticket, bob is a viewer and gets 403, a call with no token gets 401, and a token with one changed character gets invalid_token.
What you will learn
- Make a Spring Boot API trust Keycloak's tokens with one issuer-uri property
- Map Keycloak realm roles to Spring authorities with a small converter
- Read 401, 403 and invalid_token answers and know which check stopped each call
- Sign a React app in with oidc-client-ts using the code flow with PKCE, and allow only its origin with CORS
Before you start
- How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
- Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
In the JWT lecture, the Spring Boot app signed its own tokens. Here it stops doing that. Keycloak, an identity provider running in Docker, owns the users, the login page and the signing keys. The API only checks the tokens it's given, and a React app does the sign-in. The ticket desk has two users: alice, an agent, and bob, a viewer.
Keycloak and the realm
Keycloak 26.4 runs from compose.yaml with start-dev --import-realm, which loads a realm file at startup. It listens on port 8280 here. The realm desk has two roles, agent and viewer, and one client for the React app, desk-web:
- a public client, because a browser app can't keep a secret,
- the standard flow (authorization code) on, and direct password grants off,
- one allowed redirect URI,
http://localhost:5173/, - and PKCE with
S256required.
Keycloak publishes a discovery document at /realms/desk/.well-known/openid-configuration, with the issuer, the authorization and token endpoints and the jwks_uri where its public keys are. That's what the API uses next. (For the login flow itself, step by step, see How an Identity Provider Login Works.)
The API: one dependency, one property
Besides spring-boot-starter-webmvc, the pom has spring-boot-starter-security-oauth2-resource-server. Then:
spring.application.name=ticket-desk-api
server.port=8093
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8280/realms/desk
app.allowed-origin=http://localhost:5173
issuer-uri is all Spring needs. It finds the discovery document, fetches the public keys from jwks_uri, and from then on checks every token's signature, its issuer (it must be exactly this URL) and its expiry. No secret is shared between Keycloak and the API.
The rules
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(new RealmRoleConverter());
http.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(a -> a
.requestMatchers("/api/tickets").hasRole("agent")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(j -> j.jwtAuthenticationConverter(converter)));
return http.build();
}
Stateless with no session, and CSRF off, because the token travels in a header the browser never adds by itself. /api/tickets needs the role agent; everything else just needs a valid token. oauth2ResourceServer(...jwt(...)) turns on the token check, with our own converter for roles.
Keycloak's roles are in its own claim
Spring's default reads authorities from a scope claim. Keycloak puts realm roles somewhere else. alice's decoded token contains "realm_access":{"roles":["agent"]}. The converter turns those into authorities that hasRole understands:
public class RealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
@Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
Map<String, Object> realm = jwt.getClaimAsMap("realm_access");
if (realm == null || !(realm.get("roles") instanceof Collection<?> roles)) {
return List.of();
}
return roles.stream()
.<GrantedAuthority>map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList();
}
}
hasRole("agent") looks for ROLE_agent, hence the prefix. A small /api/me endpoint prints what Spring ended up with:
alice: {"user":"alice","authorities":["FACTOR_BEARER","ROLE_agent"]}
bob: {"user":"bob","authorities":["FACTOR_BEARER","ROLE_viewer"]}
FACTOR_BEARER isn't from Keycloak. Spring Security adds it itself, to record that the user authenticated with a bearer token.
Four calls, four answers
- No token:
HTTP/1.1 401withWWW-Authenticate: Bearer. - alice's token with an "x" added: 401,
invalid_token. The signature no longer matches. - bob: a valid token without the agent role, so 403,
insufficient_scope. - alice: 200 and
[{"id":7,"title":"Printer jammed","status":"OPEN"}].
CORS: only the React app's origin
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of(origin));
config.setAllowedMethods(List.of("GET"));
config.setAllowedHeaders(List.of("Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
The React app runs on port 5173 and the API on 8093, so the browser asks first with a preflight. From http://localhost:5173 the preflight got 200 with the allow headers. From http://localhost:3000 it got 403, Invalid CORS request. One origin, one method, one header: the browser can send the token from the real app and nothing else.
The React side: a few lines with oidc-client-ts
export const auth = new UserManager({
authority: 'http://localhost:8280/realms/desk',
client_id: 'desk-web',
redirect_uri: 'http://localhost:5173/',
response_type: 'code',
scope: 'openid',
})
oidc-client-ts (3.5.0) does the protocol work. The sign-in button calls auth.signinRedirect(), which sends the browser to Keycloak's login page with client_id, redirect_uri, response_type=code, scope=openid, a random state and a code_challenge with code_challenge_method=S256. The library adds PKCE itself and keeps the matching verifier in the browser.
After the login, Keycloak redirects back to http://localhost:5173/? with the same state and a one-time code. The app sees code= in the URL and calls signinRedirectCallback(), which checks the state, swaps the code plus the verifier for tokens at Keycloak's token endpoint (the answer had token_type: Bearer and expires_in: 300), and then the app cleans the URL with replaceState. From then on every API call carries Authorization: Bearer .... No token ever appears in the address bar.
Common mistakes
- Expecting
hasRoleto work out of the box. Without a converter, Keycloak's realm roles never become authorities, and every call is 403. - An issuer that doesn't match exactly.
localhostin the API and a container name in the token are different issuers, and every token is refused. - A confidential client with a secret in the React bundle. Anyone can read the bundle. Use a public client with PKCE.
- CORS set to
*. Name the real origin.
Try it yourself
Give bob the agent role in Keycloak and call /api/tickets again with his old token. What do you get, and what does bob have to do before the new role counts?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
