Sub topic 9
From claims to GrantedAuthorities
This chapter assumes you can write a Spring Boot controller and a SecurityFilterChain bean. It also assumes you know what a JWT claim is (the previous chapters covered iss, sub, aud, exp, and the scope claim). By the end, you will know how Spring Security turns the claims of a validated token into the authorities your authorization rules check.
Why authority mapping exists
Validating a JWT proves that the token is genuine and current. It does not say what the caller may do. Spring Security's authorization rules, such as hasAuthority("SCOPE_admin") or hasRole("ADMIN"), work on GrantedAuthority objects. A GrantedAuthority is an object that holds one permission string, for example SCOPE_orders.read.
Something has to translate claims into those objects. In a resource server, that is a converter. It runs after the JwtDecoder has accepted the token and before any authorization rule runs.
The default mapping
If you configure nothing, Spring Security uses a JwtAuthenticationConverter with a default JwtGrantedAuthoritiesConverter. The default converter does the following:
- It looks for the claim named
scope, and if that is missing, the claim namedscp. - If the claim is a space-separated string (
"orders.read orders.write"), it splits the string. If the claim is a collection, it uses each element. - It prefixes every value with
SCOPE_.
So this payload:
{
"sub": "alice",
"scope": "orders.read orders.write"
}produces two authorities: SCOPE_orders.read and SCOPE_orders.write. That is why the earlier filter chain used hasAuthority("SCOPE_admin"). The prefix is part of the authority string, so a rule written as hasAuthority("admin") never matches.
The resulting Authentication is a JwtAuthenticationToken. Its name is the sub claim, its principal is the Jwt, and its authorities are the converted list.
Scopes, roles, and the ROLE_ prefix
Spring Security distinguishes two ways of writing the same idea.
| Rule | What it checks |
|---|---|
| `hasAuthority("SCOPE_admin")` | An authority exactly equal to `SCOPE_admin` |
| `hasAuthority("ROLE_ADMIN")` | An authority exactly equal to `ROLE_ADMIN` |
| `hasRole("ADMIN")` | An authority exactly equal to `ROLE_ADMIN` (the prefix is added for you) |
A role is only an authority whose name starts with ROLE_. The method hasRole adds that prefix before comparing. A common error is to call hasRole("SCOPE_admin"), which checks for ROLE_SCOPE_admin and always fails.
Scopes and roles come from different places in OAuth2. A scope describes what the client application was allowed to ask for. A role usually describes the user, and many authorization servers put it in a custom claim such as roles, groups, or a nested structure. The default converter reads only scopes, so roles need your own mapping.
Reading a custom claim
To read authorities from a different claim, configure the JwtGrantedAuthoritiesConverter and plug it into a JwtAuthenticationConverter:
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("roles");
authorities.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
return converter;
}
// In the filter chain:
// .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))With {"roles": ["ADMIN", "AUDITOR"]} in the token, this yields ROLE_ADMIN and ROLE_AUDITOR, and hasRole("ADMIN") now passes.
Note what changed. The new converter replaces the default scope mapping. A token's scope claim no longer produces SCOPE_ authorities, so any rule that uses hasAuthority("SCOPE_admin") stops matching. If you need both, you must combine them.
Combining scopes and roles
To keep scope authorities and add role authorities, write a converter that runs two JwtGrantedAuthoritiesConverter instances and merges the results. JwtAuthenticationConverter accepts any Converter<Jwt, Collection<GrantedAuthority>>, so a lambda works:
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter scopes = new JwtGrantedAuthoritiesConverter();
JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles");
roles.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
Set<GrantedAuthority> merged = new LinkedHashSet<>();
merged.addAll(scopes.convert(jwt));
merged.addAll(roles.convert(jwt));
return merged;
});
return converter;
}convert returns a collection, which is empty when the claim is absent. It does not return null for a missing claim, so the merge is safe for tokens that carry only one of the two claims.
Nested claims
Some providers do not put roles at the top level. Keycloak, for example, places realm roles under realm_access.roles. setAuthoritiesClaimName accepts only a top-level name here, so you write the extraction yourself:
@Bean
JwtAuthenticationConverter keycloakConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
Map<String, Object> realmAccess = jwt.getClaimAsMap("realm_access");
if (realmAccess == null || !(realmAccess.get("roles") instanceof Collection<?> roles)) {
return List.of();
}
return roles.stream()
.map(String::valueOf)
.<GrantedAuthority>map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList();
});
return converter;
}The code checks for null and for the wrong type before it reads the list. Claims come from outside your system. A token from a trusted issuer is still data, and a missing or oddly shaped claim should give the caller no authorities, not an exception.
Choosing the principal name
By default the authentication name is the sub claim. Some providers put a readable name in another claim, such as preferred_username. Set it on the converter:
converter.setPrincipalClaimName("preferred_username");This changes authentication.getName(), which appears in logs and in @PreAuthorize expressions that use authentication.name. It does not change the Jwt that @AuthenticationPrincipal Jwt jwt injects, so jwt.getSubject() still returns sub.
Failure modes
- Every request returns 403 after a change. The converter now produces different authority strings than the rules expect. Log
authentication.getAuthorities()in a test and compare. - Roles never appear. The claim name differs from what you configured, or the provider does not include it in access tokens. Many providers put roles in the ID token only, or require a mapper or a setting to add them to the access token.
- Authorities have a double prefix. Your claim already contains
ROLE_ADMINand you also set the prefix toROLE_. Either set the prefix to an empty string or strip it from the claim values. - Scope claim arrives as a list. The default converter handles both a string and a collection. A custom converter that calls
getClaimAsString("scope")does not. - Authority list is huge. Mapping every group in a large directory into authorities increases memory per request. Map only what your rules use.
What the mapping does not do
Authority mapping is a read-only translation of a token that was already validated. It does not check the audience, the issuer, or the expiry. Those checks belong to the JwtDecoder. It also does not call the authorization server, so authorities reflect the token's state when it was issued. If a user loses a role, a token issued earlier still carries it until it expires.
Exercise
A token contains {"scope": "orders.read", "roles": ["ADMIN"]}. You configure a JwtGrantedAuthoritiesConverter with setAuthoritiesClaimName("roles") and setAuthorityPrefix("ROLE"), and set it as the only authorities converter. Which of these rules pass for this caller: hasRole("ADMIN"), hasAuthority("SCOPEorders.read"), hasAuthority("ROLEADMIN"), hasRole("ROLEADMIN")?
Show answer
hasRole("ADMIN") and hasAuthority("ROLEADMIN") pass, because the converter produces ROLEADMIN. hasAuthority("SCOPEorders.read") fails because the custom converter replaced the default scope mapping. hasRole("ROLEADMIN") fails because it checks for ROLEROLEADMIN.
Exercise
Write a converter lambda body that returns an empty authority list when a token has no "groups" claim, and otherwise maps each group name to an authority prefixed with "GROUP_". What Jwt method reads the claim as a list of strings?
Show answer
Use jwt.getClaimAsStringList("groups"), which returns null when the claim is absent. For example: List<String> groups = jwt.getClaimAsStringList("groups"); if (groups == null) return List.of(); return groups.stream().map(g -> new SimpleGrantedAuthority("GROUP_" + g)).collect(Collectors.toList());