Mappare i claim JWT sulle autorità di Spring
Impari come un resource server converte i claim JWT in GrantedAuthorities di Spring Security usando JwtAuthenticationConverter, per un controllo degli accessi granulare.
Mappare i claim JWT sulle autorità di Spring è una lezione Spring Security 6 & JWT Authentication gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Security 6 & JWT Authentication, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Impara Java con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Mappare i claim JWT sulle autorità di Spring» è gratuita?
Sì — il testo completo di «Mappare i claim JWT sulle autorità di Spring» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Security 6 & JWT Authentication, passa a CoddyKit PRO. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.
Cosa imparerò in «Mappare i claim JWT sulle autorità di Spring»?
Impari come un resource server converte i claim JWT in GrantedAuthorities di Spring Security usando JwtAuthenticationConverter, per un controllo degli accessi granulare. Eserciti Spring Security 6 & JWT Authentication con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Spring Security 6 & JWT Authentication?
Non è richiesta alcuna esperienza precedente. Spring Security 6 & JWT Authentication su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Mappare i claim JWT sulle autorità di Spring»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Spring Security 6 & JWT Authentication?
Sì. Ogni lezione Spring Security 6 & JWT Authentication include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Configurazione del Resource Server
- Decodifica e convalida dei JWT
- Applicazione di scope e claim
- Mappare i claim JWT sulle autorità di Spring