0Pricing
Spring Security 6 & JWT Authentication · 강의

JWT 클레임을 Spring 권한으로 매핑하기

리소스 서버가 JwtAuthenticationConverter를 사용해 JWT 클레임을 세밀한 접근 제어에 필요한 Spring Security GrantedAuthorities로 변환하는 방식을 배워 보세요.

JWT 클레임을 Spring 권한으로 매핑하기은(는) CoddyKit의 무료 Spring Security 6 & JWT Authentication 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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_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.

자주 묻는 질문

“JWT 클레임을 Spring 권한으로 매핑하기” 강의는 무료인가요?

네 — “JWT 클레임을 Spring 권한으로 매핑하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Security 6 & JWT Authentication 강의 전체를 잠금 해제할 수 있습니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

“JWT 클레임을 Spring 권한으로 매핑하기”에서 뭘 배우나요?

리소스 서버가 JwtAuthenticationConverter를 사용해 JWT 클레임을 세밀한 접근 제어에 필요한 Spring Security GrantedAuthorities로 변환하는 방식을 배워 보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Security 6 & JWT Authentication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Security 6 & JWT Authentication을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Security 6 & JWT Authentication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“JWT 클레임을 Spring 권한으로 매핑하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Security 6 & JWT Authentication 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Security 6 & JWT Authentication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 리소스 서버 설정
  2. JWT 디코딩 및 검증
  3. 범위 및 클레임 적용
  4. JWT 클레임을 Spring 권한으로 매핑하기
← Spring Security 6 & JWT Authentication(으)로 돌아가기