JWT-Claims Spring Authorities zuordnen
Lernen Sie, wie ein Resource Server JWT-Claims mithilfe von JwtAuthenticationConverter in Spring Security GrantedAuthorities umwandelt, um eine fein abgestufte Zugriffskontrolle zu ermöglichen.
JWT-Claims Spring Authorities zuordnen ist eine kostenlose Spring Security 6 & JWT Authentication-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Security 6 & JWT Authentication-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
From Claims to Authorities
A resource server validates a JWT, but to enforce access it needs Spring GrantedAuthority objects. The bridge between raw claims and authorities is the JwtAuthenticationConverter.
The Default Scope Mapping
By default Spring reads the scope or scp claim, splits it on spaces, and prefixes each value with SCOPE_. So a scope of read becomes the authority SCOPE_read.
// scope: 'read write' -> SCOPE_read, SCOPE_writeChecking Scope Authorities
You can require these authorities in your security config or with annotations.
http.authorizeHttpRequests(auth -> auth
.requestMatchers('/api/data').hasAuthority('SCOPE_read'));The Problem with Roles
Many identity providers put roles in a custom claim like roles or realm_access.roles, not in scope. The default converter ignores those, so you must customize it.
Building a Custom Converter
Create a JwtGrantedAuthoritiesConverter and point it at the claim that holds your roles.
JwtGrantedAuthoritiesConverter c = new JwtGrantedAuthoritiesConverter();
c.setAuthoritiesClaimName('roles');
c.setAuthorityPrefix('ROLE_');Wrapping in JwtAuthenticationConverter
Wrap the authorities converter inside a JwtAuthenticationConverter, which produces the final authentication token.
JwtAuthenticationConverter conv = new JwtAuthenticationConverter();
conv.setJwtGrantedAuthoritiesConverter(c);Registering the Converter
Tell the resource server to use your converter inside the JWT configuration.
http.oauth2ResourceServer(o -> o
.jwt(j -> j.jwtAuthenticationConverter(conv)));Nested Claims
Some providers nest roles, e.g. Keycloak uses realm_access.roles. The simple converter cannot read nested paths, so write a lambda converter that drills into the structure.
Converter<Jwt, Collection<GrantedAuthority>> conv = jwt -> {
Map<String,Object> realm = jwt.getClaim('realm_access');
List<String> roles = (List<String>) realm.get('roles');
return roles.stream()
.map(r -> new SimpleGrantedAuthority('ROLE_' + r))
.collect(Collectors.toList());
};Combining Scopes and Roles
You may want both scope-based and role-based authorities. Merge two converters' results so a single principal carries both SCOPE_ and ROLE_ authorities.
Customizing the Principal Name
By default the principal name is the sub claim. Override setPrincipalClaimName if you prefer to identify users by, say, preferred_username.
conv.setPrincipalClaimName('preferred_username');Verifying the Mapping
Test with a mock JWT that carries the roles claim and assert the request succeeds only when the expected authority is present.
mockMvc.perform(get('/api/admin')
.with(jwt().authorities(new SimpleGrantedAuthority('ROLE_admin'))))
.andExpect(status().isOk());Quick Check
Test your understanding of claim-to-authority mapping.
Recap
You learned to map JWT claims to Spring authorities:
- Default mapping turns
scopeintoSCOPE_authorities - Use
JwtGrantedAuthoritiesConverterto read custom role claims - Write a lambda converter for nested claims like
realm_access.roles - Register it via
jwtAuthenticationConverter
This gives your resource server precise, claim-driven access control.
Lerne Java mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „JWT-Claims Spring Authorities zuordnen“ kostenlos?
Ja — der vollständige Text von „JWT-Claims Spring Authorities zuordnen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Security 6 & JWT Authentication-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „JWT-Claims Spring Authorities zuordnen“?
Lernen Sie, wie ein Resource Server JWT-Claims mithilfe von JwtAuthenticationConverter in Spring Security GrantedAuthorities umwandelt, um eine fein abgestufte Zugriffskontrolle zu ermöglichen. Du übst Spring Security 6 & JWT Authentication mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Security 6 & JWT Authentication zu starten?
Keine Vorkenntnisse erforderlich. Spring Security 6 & JWT Authentication auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „JWT-Claims Spring Authorities zuordnen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Security 6 & JWT Authentication-Lektion Code schreiben und ausführen?
Ja. Jede Spring Security 6 & JWT Authentication-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Ressourcenserver einrichten
- JWTs decodieren und validieren
- Scopes und Claims durchsetzen
- JWT-Claims Spring Authorities zuordnen