Сопоставление утверждений JWT с полномочиями Spring
Узнайте, как сервер ресурсов преобразует утверждения JWT в GrantedAuthorities Spring Security с помощью JwtAuthenticationConverter для детального управления доступом
«Сопоставление утверждений JWT с полномочиями Spring» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Изучай Java с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Сопоставление утверждений JWT с полномочиями Spring» бесплатный?
Да — полный текст урока «Сопоставление утверждений JWT с полномочиями Spring» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Чему я научусь в уроке «Сопоставление утверждений JWT с полномочиями Spring»?
Узнайте, как сервер ресурсов преобразует утверждения JWT в GrantedAuthorities Spring Security с помощью JwtAuthenticationConverter для детального управления доступом Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?
Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Сопоставление утверждений JWT с полномочиями Spring»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?
Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка сервера ресурсов
- Декодирование и проверка JWT
- Проверка областей и утверждений
- Сопоставление утверждений JWT с полномочиями Spring