Spring › Feature

Mapping Keycloak 26 OIDC roles in Spring Security 6

Fix 403 errors from Spring Security 6's default JWT converter with Keycloak 26.8.2 by mapping realm and client roles across API and web filter chains.

Mapping Keycloak 26 OIDC roles in Spring Security 6

Spring Security 6’s default JwtGrantedAuthoritiesConverter reads only scope/scp claims, so Keycloak 26’s realm_access.roles and resource_access.<client>.roles return 403 Forbidden under @PreAuthorize. This post shows how to map both role layers, enforce aud validation, and run stateless API and stateful oauth2Login() filter chains side by side on Spring Boot 3.4.5 and Keycloak 26.8.2.

The code and observed outputs below were verified on OpenJDK 21, Spring Boot 3.4.5 (Spring Security 6.4.5), and Keycloak 26.8.2 (quay.io/keycloak/keycloak:26.8.2).

Why the default JWT converter returns 403

Even with a valid, signed Keycloak Access Token that includes ADMIN and order:write, Spring Security rejects @PreAuthorize("hasRole('ADMIN')") with 403 Forbidden out of the box.

When you configure only oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())), Spring Security 6.4.5 delegates authority extraction to JwtGrantedAuthoritiesConverter. That default converter inspects only the scope or scp claim and prefixes each entry with SCOPE_. It ignores Keycloak’s realm_access and resource_access claims completely.

Here is an excerpt from the Access Token Keycloak 26.8.2 issued for alice (Realm Roles ADMIN, USER; spring-api Client Roles order:write, order:read):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "iss": "http://localhost:18280/realms/demo-realm",
  "sub": "660f53c3-dda1-4c10-a396-020f499b5a54",
  "aud": "spring-api",
  "azp": "spring-web",
  "preferred_username": "alice",
  "scope": "openid email profile",
  "realm_access": {
    "roles": ["ADMIN", "USER"]
  },
  "resource_access": {
    "spring-api": {
      "roles": ["order:write", "order:read"]
    }
  }
}

Sending that token to Spring Boot 3.4.5 without a custom converter authenticates the request, but populates authorities with SCOPE_* values only:

1
2
3
4
5
6
7
--- GET /api/me (alice, default converter) ---
HTTP/1.1 200
{"aud":["spring-api"],"principal":"660f53c3-dda1-4c10-a396-020f499b5a54","preferred_username":"alice","authorities":["SCOPE_email","SCOPE_openid","SCOPE_profile"]}

--- GET /api/admin (alice, @PreAuthorize("hasRole('ADMIN')")) ---
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

The principal also defaults to the sub UUID instead of preferred_username, and both /api/admin and /api/orders (@PreAuthorize("hasAuthority('order:write')")) return 403 Forbidden.

Keycloak claim structure and role mapping strategy

Separating prefixes by claim type keeps authorization rules predictable as services grow.

Keycloak claimSpring Security authorityExpression exampleBest fit
scope / scpSCOPE_<scope>hasAuthority('SCOPE_profile')OAuth 2.0 delegated client scopes
realm_access.rolesROLE_<role>hasRole('ADMIN')Coarse-grained roles shared across the Keycloak Realm
resource_access.<clientId>.roles<clientRole>hasAuthority('order:write')Fine-grained permissions scoped to one API (spring-api)

Prefixing Realm roles with ROLE_ matches hasRole(), while keeping client roles unprefixed (order:write) lets hasAuthority() target API-specific permissions without naming collisions.

When not to pack permissions into JWT claims

Avoid moving every domain permission into Keycloak roles. Dozens or hundreds of roles bloat the JWT and can trip reverse-proxy HTTP header limits. JWT claims also stay valid until exp, so revoking a role in Keycloak won’t block an active token immediately. For per-resource permissions (ABAC/ReBAC) or instant revocation, keep only coarse-grained roles in the token and evaluate fine-grained rules in your application database or policy engine.

Configuring Resource Server and custom JWT role conversion

Add spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-oauth2-resource-server, and spring-boot-starter-oauth2-client on Spring Boot 3.4.5, then configure both Resource Server and OAuth2 Client in application.yml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# src/main/resources/application.yml
app:
  security:
    resource-client-id: spring-api

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:18280/realms/demo-realm
          audiences:
            - spring-api
      client:
        registration:
          keycloak:
            client-id: spring-web
            client-secret: ${KEYCLOAK_CLIENT_SECRET}
            scope: openid, profile, email
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          keycloak:
            issuer-uri: http://localhost:18280/realms/demo-realm
            user-name-attribute: preferred_username

Setting spring.security.oauth2.resourceserver.jwt.audiences pairs directly with Keycloak 26.8.2’s oidc-audience-mapper (included.client.audience: spring-api). Spring Boot 3.4.5 validates aud automatically without a custom JwtDecoder bean. For the broader boundary between Access Tokens, ID Tokens, and audience checks, see OAuth 2.0 vs. OIDC token roles.

Next, implement KeycloakJwtAuthoritiesConverter to preserve default SCOPE_* entries while extracting realm_access.roles and resource_access.<clientId>.roles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// src/main/java/com/example/keycloakdemo/security/KeycloakJwtAuthoritiesConverter.java
package com.example.keycloakdemo.security;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
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.JwtGrantedAuthoritiesConverter;

public class KeycloakJwtAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    private final String resourceClientId;
    private final JwtGrantedAuthoritiesConverter defaultConverter = new JwtGrantedAuthoritiesConverter();

    public KeycloakJwtAuthoritiesConverter(String resourceClientId) {
        this.resourceClientId = resourceClientId;
    }

    @Override
    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Set<GrantedAuthority> authorities = new LinkedHashSet<>();

        // 1. Preserve default scope/scp claims (SCOPE_*)
        Collection<GrantedAuthority> scopeAuthorities = defaultConverter.convert(jwt);
        if (scopeAuthorities != null) {
            authorities.addAll(scopeAuthorities);
        }

        // 2. Realm roles: realm_access.roles -> ROLE_<role>
        extractRealmRoles(jwt.getClaimAsMap("realm_access"), authorities);

        // 3. Client roles: resource_access.<clientId>.roles -> <clientRole>
        extractClientRoles(jwt.getClaimAsMap("resource_access"), resourceClientId, authorities);

        return authorities;
    }

    static void extractRealmRoles(Map<String, Object> realmAccess, Set<GrantedAuthority> target) {
        if (realmAccess == null) {
            return;
        }
        Object rolesObj = realmAccess.get("roles");
        if (rolesObj instanceof Collection<?> roles) {
            for (Object role : roles) {
                if (role instanceof String roleName && !roleName.isBlank()) {
                    target.add(new SimpleGrantedAuthority("ROLE_" + roleName));
                }
            }
        }
    }

    static void extractClientRoles(
            Map<String, Object> resourceAccess,
            String clientId,
            Set<GrantedAuthority> target
    ) {
        if (resourceAccess == null || clientId == null || clientId.isBlank()) {
            return;
        }
        Object clientObj = resourceAccess.get(clientId);
        if (clientObj instanceof Map<?, ?> clientMap) {
            Object rolesObj = clientMap.get("roles");
            if (rolesObj instanceof Collection<?> roles) {
                for (Object role : roles) {
                    if (role instanceof String roleName && !roleName.isBlank()) {
                        target.add(new SimpleGrantedAuthority(roleName));
                    }
                }
            }
        }
    }
}

The resourceAccess == null guard isn’t theoretical. For bob, who only holds the USER Realm Role and no client roles, Keycloak 26.8.2 emits resource_access: null rather than an empty object:

1
2
3
4
5
6
7
{
  "preferred_username": "bob",
  "realm_access": {
    "roles": ["USER"]
  },
  "resource_access": null
}

Coexisting API and web SecurityFilterChains with OAuth2 Login

When one Spring Boot app serves both stateless REST APIs (/api/**) and browser-based OIDC pages (/web/**), split the rules into ordered SecurityFilterChain beans using securityMatcher, following the same isolation pattern from splitting JWT and session filter chains in Spring Security.

flowchart TD
    Req["Incoming HTTP request"] --> Match{"Path matcher"}
    Match -->|"/api/** (@Order 1)"| ApiChain["Stateless Resource Server\n(KeycloakJwtAuthoritiesConverter)"]
    Match -->|"/web/**, /oauth2/** (@Order 2)"| WebChain["Stateful oauth2Login()\n(KeycloakOidcAuthoritiesMapper)"]
    ApiChain --> ApiRes["Unauthenticated 401 / JWT role authz"]
    WebChain --> WebRes["Unauthenticated 302 -> Keycloak Auth URL"]

Because oauth2Login() produces an OidcUserAuthority instead of calling JwtAuthenticationConverter, web sessions need a separate GrantedAuthoritiesMapper to expose the same ROLE_* and client authorities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/main/java/com/example/keycloakdemo/security/KeycloakOidcAuthoritiesMapper.java
package com.example.keycloakdemo.security;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;

public class KeycloakOidcAuthoritiesMapper implements GrantedAuthoritiesMapper {

    private final String resourceClientId;

    public KeycloakOidcAuthoritiesMapper(String resourceClientId) {
        this.resourceClientId = resourceClientId;
    }

    @Override
    public Collection<? extends GrantedAuthority> mapAuthorities(
            Collection<? extends GrantedAuthority> authorities
    ) {
        Set<GrantedAuthority> mapped = new LinkedHashSet<>(authorities);

        for (GrantedAuthority authority : authorities) {
            if (authority instanceof OidcUserAuthority oidcAuthority) {
                extractFromClaims(oidcAuthority.getIdToken().getClaims(), mapped);
                if (oidcAuthority.getUserInfo() != null) {
                    extractFromClaims(oidcAuthority.getUserInfo().getClaims(), mapped);
                }
            }
        }
        return mapped;
    }

    @SuppressWarnings("unchecked")
    private void extractFromClaims(Map<String, Object> claims, Set<GrantedAuthority> target) {
        if (claims == null) {
            return;
        }
        Object realmAccess = claims.get("realm_access");
        if (realmAccess instanceof Map<?, ?> realmMap) {
            KeycloakJwtAuthoritiesConverter.extractRealmRoles((Map<String, Object>) realmMap, target);
        }
        Object resourceAccess = claims.get("resource_access");
        if (resourceAccess instanceof Map<?, ?> resourceMap) {
            KeycloakJwtAuthoritiesConverter.extractClientRoles(
                    (Map<String, Object>) resourceMap, resourceClientId, target);
        }
    }
}

Wire both filter chains in SecurityConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// src/main/java/com/example/keycloakdemo/security/SecurityConfig.java
package com.example.keycloakdemo.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Value("${app.security.resource-client-id:spring-api}")
    private String resourceClientId;

    @Bean
    public JwtAuthenticationConverter keycloakJwtAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(new KeycloakJwtAuthoritiesConverter(resourceClientId));
        converter.setPrincipalClaimName("preferred_username");
        return converter;
    }

    @Bean
    public GrantedAuthoritiesMapper keycloakOidcAuthoritiesMapper() {
        return new KeycloakOidcAuthoritiesMapper(resourceClientId);
    }

    @Bean
    @Order(1)
    public SecurityFilterChain apiSecurityFilterChain(
            HttpSecurity http,
            JwtAuthenticationConverter keycloakJwtAuthenticationConverter
    ) throws Exception {
        http
                .securityMatcher("/api/**")
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt.jwtAuthenticationConverter(keycloakJwtAuthenticationConverter))
                );
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain webSecurityFilterChain(
            HttpSecurity http,
            GrantedAuthoritiesMapper keycloakOidcAuthoritiesMapper
    ) throws Exception {
        http
                .securityMatcher("/web/**", "/login/**", "/oauth2/**", "/public/**")
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/public/**").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2Login(oauth2 -> oauth2
                        .userInfoEndpoint(userInfo -> userInfo
                                .userAuthoritiesMapper(keycloakOidcAuthoritiesMapper)
                        )
                );
        return http.build();
    }
}

The API controller enforces Realm and client permissions with @PreAuthorize (the /api/me excerpt below omits the aud and preferred_username fields read from JwtAuthenticationToken that appear in the live response logs):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/main/java/com/example/keycloakdemo/web/DemoApiController.java
@RestController
@RequestMapping("/api")
public class DemoApiController {

    @GetMapping("/me")
    public Map<String, Object> me(Authentication authentication) {
        List<String> authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .sorted()
                .toList();
        return Map.of("principal", authentication.getName(), "authorities", authorities);
    }

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public Map<String, Object> admin(Authentication authentication) {
        return Map.of("endpoint", "/api/admin", "user", authentication.getName());
    }

    @PostMapping("/orders")
    @PreAuthorize("hasAuthority('order:write')")
    public Map<String, Object> createOrder(Authentication authentication) {
        return Map.of("endpoint", "/api/orders", "status", "created", "user", authentication.getName());
    }
}

Verification results from live calls and tests

I ran Keycloak 26.8.2 in Docker (localhost:18280) alongside the Spring Boot 3.4.5 JAR (localhost:18281) to verify role separation and filter-chain routing.

For local curl testing, I temporarily enabled directAccessGrantsEnabled: true (ROPC) on the spring-web test client to fetch Access Tokens from the CLI. Never enable ROPC in production—use Authorization Code + PKCE (S256) as covered in why OAuth 2.1 and RFC 9700 mandate PKCE (S256).

With KeycloakJwtAuthoritiesConverter enabled, alice and bob receive distinct authorization results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--- GET /api/me (alice) ---
HTTP/1.1 200
{"principal":"alice","aud":["spring-api"],"authorities":["ROLE_ADMIN","ROLE_USER","SCOPE_email","SCOPE_openid","SCOPE_profile","order:read","order:write"],"preferred_username":"alice"}

--- GET /api/admin (alice) & POST /api/orders (alice) ---
HTTP/1.1 200  {"endpoint":"/api/admin","user":"alice"}
HTTP/1.1 200  {"status":"created","endpoint":"/api/orders","user":"alice"}

--- GET /api/me (bob) ---
HTTP/1.1 200
{"principal":"bob","aud":["spring-api"],"authorities":["ROLE_USER","SCOPE_email","SCOPE_openid","SCOPE_profile"],"preferred_username":"bob"}

--- GET /api/admin (bob) & POST /api/orders (bob) ---
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

alice passes both /api/admin and /api/orders with 200 OK. bob—whose token has resource_access: null—succeeds on /api/me without a NullPointerException and receives 403 Forbidden on both protected endpoints.

Unauthenticated requests also split cleanly across the two filter chains:

1
2
3
4
5
6
7
8
9
10
11
12
13
--- GET /api/me (unauthenticated) ---
HTTP/1.1 401
WWW-Authenticate: Bearer

--- GET /web/dashboard (unauthenticated) ---
HTTP/1.1 302
Set-Cookie: JSESSIONID=<MASKED_SESSION_ID>; Path=/; HttpOnly
Location: http://localhost:18281/oauth2/authorization/keycloak

--- GET /oauth2/authorization/keycloak ---
HTTP/1.1 302
Set-Cookie: JSESSIONID=<MASKED_SESSION_ID>; Path=/; HttpOnly
Location: http://localhost:18280/realms/demo-realm/protocol/openid-connect/auth?response_type=code&client_id=spring-web&scope=openid%20profile%20email&state=<MASKED_STATE>&redirect_uri=http://localhost:18281/login/oauth2/code/keycloak&nonce=<MASKED_NONCE>

/api/me returns 401 Unauthorized without creating a session, while /web/dashboard redirects through /oauth2/authorization/keycloak to Keycloak 26.8.2’s authorization endpoint.

Scope note: for oauth2Login(), this verification covered the unauthenticated redirect chain up to Keycloak’s Auth Endpoint plus JUnit 5/MockMvc tests (5/5 passing, including KeycloakOidcAuthoritiesMapper extracting ROLE_ADMIN, ROLE_USER, and order:write from OidcUserAuthority). Interactive browser form login through the callback exchange to a 200 OK /web/dashboard response wasn’t executed in this run.

Production caveats and checklist

Four edge cases regularly show up when moving this setup to production.

Watch out for JwtAuthenticationConverter bean auto-detection In Spring Security 6.4.5, registering a JwtAuthenticationConverter bean in the ApplicationContext causes even oauth2.jwt(Customizer.withDefaults()) on another filter chain to pick it up automatically. If different chains need different converters (or the default one), instantiate the converter directly inside each chain instead of exposing a single global @Bean.

  1. Always validate aud: Leaving spring.security.oauth2.resourceserver.jwt.audiences unset lets tokens issued for another client in the same Keycloak Realm pass verification. Pair it with Keycloak’s oidc-audience-mapper.
  2. Guard against resource_access: null: Users with no client roles receive resource_access: null or an omitted claim. Keep null and type checks in both your JWT converter and OIDC mapper.
  3. Check ID Token / UserInfo mappers for web sessions: KeycloakOidcAuthoritiesMapper reads ID Token and UserInfo claims rather than the Access Token. If web roles come up empty, verify that Add to ID token or Add to userinfo is enabled on Keycloak’s roles Client Scope mappers.
  4. Disable ROPC in production: Turn off directAccessGrantsEnabled on production clients and enforce Authorization Code + PKCE (S256).

References

Most Resource Server support is collected into spring-security-oauth2-resource-server. However, the support for decoding and verifying JWTs is in spring-security-oauth2-jose, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens.
HttpSecurity.oauth2Login() provides a number of configuration options for customizing OAuth 2.0 Login. The main configuration options are grouped into their protocol endpoint counterparts.
The page you’re looking for does not exist.
This post is licensed under CC BY 4.0 by the author.