0Pricing
Spring Security 6 & JWT Authentication · Lekcja

Mapowanie claims JWT na uprawnienia Spring

Dowiedz się, jak serwer zasobów konwertuje claims JWT na GrantedAuthorities Spring Security przy użyciu JwtAuthenticationConverter, aby zapewnić szczegółową kontrolę dostępu.

Mapowanie claims JWT na uprawnienia Spring to bezpłatna lekcja Spring Security 6 & JWT Authentication na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Security 6 & JWT Authentication, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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_write

Checking 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 scope into SCOPE_ authorities
  • Use JwtGrantedAuthoritiesConverter to 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.

Często zadawane pytania

Czy lekcja „Mapowanie claims JWT na uprawnienia Spring” jest bezpłatna?

Tak — pełny tekst „Mapowanie claims JWT na uprawnienia Spring” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Security 6 & JWT Authentication, przejdź na CoddyKit PRO. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.

Co nauczysz się w „Mapowanie claims JWT na uprawnienia Spring”?

Dowiedz się, jak serwer zasobów konwertuje claims JWT na GrantedAuthorities Spring Security przy użyciu JwtAuthenticationConverter, aby zapewnić szczegółową kontrolę dostępu. Ćwiczysz Spring Security 6 & JWT Authentication z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Security 6 & JWT Authentication?

Nie wymagamy żadnego doświadczenia. Spring Security 6 & JWT Authentication w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Mapowanie claims JWT na uprawnienia Spring”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Security 6 & JWT Authentication?

Tak. Każda lekcja Spring Security 6 & JWT Authentication zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Konfiguracja serwera zasobów
  2. Dekodowanie i walidacja tokenów JWT
  3. Wymuszanie zakresów i claims
  4. Mapowanie claims JWT na uprawnienia Spring
← Powrót do Spring Security 6 & JWT Authentication