Spring › Feature

Spring Security 6와 Keycloak 26 OIDC 연동과 권한 매핑

Spring Boot 3.4.5와 Keycloak 26.8.2 환경에서 기본 JWT 컨버터의 403 원인을 분석하고, Realm·Client 권한 매핑과 API·Web 멀티 SecurityFilterChain 구성을 정리합니다.

Spring Security 6와 Keycloak 26 OIDC 연동과 권한 매핑

Spring Security 6의 기본 JwtGrantedAuthoritiesConverter는 scope/scp 클레임만 읽기 때문에, Keycloak 26이 발급한 Access Token의 realm_access.roles와 resource_access.<client>.roles를 @PreAuthorize에서 인식하지 못하고 403 Forbidden을 반환합니다. 이 글에서는 Spring Boot 3.4.5와 Keycloak 26.8.2 환경에서 커스텀 권한 컨버터와 aud 검증을 적용하고, Stateless API와 oauth2Login() 웹 체인을 함께 운영하는 방법을 정리합니다.

본문의 코드와 실행 결과는 OpenJDK 21, Spring Boot 3.4.5(Spring Security 6.4.5), Keycloak 26.8.2(quay.io/keycloak/keycloak:26.8.2) 환경에서 확인했습니다.

기본 JwtGrantedAuthoritiesConverter에서 403이 발생하는 이유

Keycloak에서 사용자에게 ADMIN Realm Role과 order:write Client Role을 부여하고 정상 서명된 JWT를 발급받았는데도, Spring Security의 @PreAuthorize("hasRole('ADMIN')") 엔드포인트에서 403 Forbidden이 떨어지는 경우가 많습니다.

원인은 Spring Security 6.4.5의 기본 동작에 있습니다. oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))만 설정하면 내부적으로 JwtAuthenticationConverter가 기본 JwtGrantedAuthoritiesConverter를 사용합니다. 이 기본 컨버터는 JWT의 scope 또는 scp 클레임만 읽어 SCOPE_ 접두사를 붙입니다. Keycloak 고유 클레임인 realm_access와 resource_access는 전혀 읽지 않습니다.

실제로 Keycloak 26.8.2에서 ADMIN·USER Realm Role과 spring-api의 order:write·order:read Client Role을 가진 alice 계정의 Access Token 페이로드는 다음과 같은 구조로 발급됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "iss": "http://localhost:18280/realms/demo-realm",
  "sub": "660f53c3-dda1-4c10-a396-020f499b5a54",
  "aud": "spring-api",
  "azp": "spring-web",
  "preferred_username": "alice",
  "scope": "openid email profile",
  "realm_access": {
    "roles": ["ADMIN", "USER"]
  },
  "resource_access": {
    "spring-api": {
      "roles": ["order:write", "order:read"]
    }
  }
}

이 토큰을 커스텀 컨버터 없이 Spring Boot 3.4.5 Resource Server로 보내면 인증 자체는 통과하지만 권한 목록이 SCOPE_*로만 채워집니다.

1
2
3
4
5
6
7
--- GET /api/me (alice, 기본 컨버터) ---
HTTP/1.1 200
{"aud":["spring-api"],"principal":"660f53c3-dda1-4c10-a396-020f499b5a54","preferred_username":"alice","authorities":["SCOPE_email","SCOPE_openid","SCOPE_profile"]}

--- GET /api/admin (alice, @PreAuthorize("hasRole('ADMIN')")) ---
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

principal도 preferred_username이 아니라 sub UUID로 바인딩되며, /api/admin과 @PreAuthorize("hasAuthority('order:write')")가 걸린 /api/orders 모두 403 Forbidden을 반환합니다.

Keycloak 클레임 구조와 권한 매핑 기준

Keycloak 토큰의 권한을 Spring Security의 GrantedAuthority로 옮길 때는 클레임의 의미에 따라 접두사와 역할을 분리하는 편이 유지보수에 유리합니다.

Keycloak 클레임Spring Security 매핑표현식 예시적합한 용도
scope / scpSCOPE_<scope>hasAuthority('SCOPE_profile')클라이언트 앱 위임 범위(OAuth 2.0 Scope) 확인
realm_access.rolesROLE_<role>hasRole('ADMIN')Realm 전체 서비스에 공통 적용되는 거친 역할
resource_access.<clientId>.roles<clientRole>hasAuthority('order:write')특정 API 서비스(spring-api) 전용 세분화 권한

Realm Role은 ROLE_ 접두사를 붙여 hasRole()과 맞추고, 특정 API 클라이언트에 귀속된 세분화 권한은 order:write처럼 그대로 매핑해 hasAuthority()로 검사하면 두 계층이 이름 충돌 없이 공존합니다.

JWT 클레임에 모든 권한을 넣지 말아야 하는 경우

권한 매핑이 편리하다고 해서 모든 도메인 권한을 Keycloak Role에 몰아넣는 것은 피해야 합니다. 사용자당 Role이 수십~수백 개로 늘어나면 JWT 크기가 커져 리버스 프록시나 HTTP 헤더 크기 제한에 걸리기 쉽습니다. 또한 JWT에 담긴 Role은 토큰이 만료(exp)되기 전까지 즉시 반영되지 않습니다. 조직·문서 단위의 동적 권한(ABAC/ReBAC)이나 실시간 권한 회수가 필수인 도메인이라면 JWT에는 최소한의 coarse-grained 역할만 두고, 세부 인가는 애플리케이션 DB나 정책 엔진에서 판정하는 편이 안전합니다.

Resource Server 설정과 커스텀 JWT 권한 변환기 구현

Spring Boot 3.4.5에서 spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-oauth2-resource-server, spring-boot-starter-oauth2-client 의존성을 추가한 뒤 application.yml을 구성합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# src/main/resources/application.yml
app:
  security:
    resource-client-id: spring-api

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:18280/realms/demo-realm
          audiences:
            - spring-api
      client:
        registration:
          keycloak:
            client-id: spring-web
            client-secret: ${KEYCLOAK_CLIENT_SECRET}
            scope: openid, profile, email
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          keycloak:
            issuer-uri: http://localhost:18280/realms/demo-realm
            user-name-attribute: preferred_username

여기서 눈여겨볼 설정은 spring.security.oauth2.resourceserver.jwt.audiences입니다. Keycloak 26.8.2에서 oidc-audience-mapper(included.client.audience: spring-api)로 aud 클레임에 대상 API 식별자를 포함해 두면, Spring Boot 3.4.5가 별도 JwtDecoder 커스터마이징 없이도 aud 일치 여부를 자동 검증합니다. Access Token과 ID Token의 역할 경계 및 aud 검증이 왜 필요한지는 OAuth 2.0과 OIDC의 토큰 역할 구분 글에서 더 자세히 다뤘습니다.

다음은 scope, realm_access.roles, resource_access.<clientId>.roles를 함께 변환하는 KeycloakJwtAuthoritiesConverter입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// src/main/java/com/example/keycloakdemo/security/KeycloakJwtAuthoritiesConverter.java
package com.example.keycloakdemo.security;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

public class KeycloakJwtAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    private final String resourceClientId;
    private final JwtGrantedAuthoritiesConverter defaultConverter = new JwtGrantedAuthoritiesConverter();

    public KeycloakJwtAuthoritiesConverter(String resourceClientId) {
        this.resourceClientId = resourceClientId;
    }

    @Override
    public Collection<GrantedAuthority> convert(Jwt jwt) {
        Set<GrantedAuthority> authorities = new LinkedHashSet<>();

        // 1. 기본 scope/scp 클레임(SCOPE_*) 유지
        Collection<GrantedAuthority> scopeAuthorities = defaultConverter.convert(jwt);
        if (scopeAuthorities != null) {
            authorities.addAll(scopeAuthorities);
        }

        // 2. Realm Role: realm_access.roles -> ROLE_<role>
        extractRealmRoles(jwt.getClaimAsMap("realm_access"), authorities);

        // 3. Client Role: resource_access.<clientId>.roles -> <clientRole>
        extractClientRoles(jwt.getClaimAsMap("resource_access"), resourceClientId, authorities);

        return authorities;
    }

    static void extractRealmRoles(Map<String, Object> realmAccess, Set<GrantedAuthority> target) {
        if (realmAccess == null) {
            return;
        }
        Object rolesObj = realmAccess.get("roles");
        if (rolesObj instanceof Collection<?> roles) {
            for (Object role : roles) {
                if (role instanceof String roleName && !roleName.isBlank()) {
                    target.add(new SimpleGrantedAuthority("ROLE_" + roleName));
                }
            }
        }
    }

    static void extractClientRoles(
            Map<String, Object> resourceAccess,
            String clientId,
            Set<GrantedAuthority> target
    ) {
        if (resourceAccess == null || clientId == null || clientId.isBlank()) {
            return;
        }
        Object clientObj = resourceAccess.get(clientId);
        if (clientObj instanceof Map<?, ?> clientMap) {
            Object rolesObj = clientMap.get("roles");
            if (rolesObj instanceof Collection<?> roles) {
                for (Object role : roles) {
                    if (role instanceof String roleName && !roleName.isBlank()) {
                        target.add(new SimpleGrantedAuthority(roleName));
                    }
                }
            }
        }
    }
}

extractClientRoles의 resourceAccess == null 방어 분기는 꼭 필요합니다. 실제 Keycloak 26.8.2에서 USER Realm Role만 있고 Client Role이 없는 bob 계정의 토큰을 확인해 보면 resource_access가 빈 맵이 아니라 null로 내려옵니다.

1
2
3
4
5
6
7
{
  "preferred_username": "bob",
  "realm_access": {
    "roles": ["USER"]
  },
  "resource_access": null
}

API와 Web 멀티 SecurityFilterChain 및 OAuth2 Login 연동

하나의 Spring Boot 애플리케이션에서 외부 클라이언트용 무상태 REST API(/api/**)와 브라우저용 OIDC 로그인 페이지(/web/**)를 함께 제공해야 한다면, 이전 Spring 멀티 SecurityFilterChain 분리 글에서 다룬 것처럼 @Order와 securityMatcher로 체인을 명확히 나눕니다.

flowchart TD
    Req["HTTP 요청 수신"] --> Match{"경로 매칭"}
    Match -->|"/api/** (@Order 1)"| ApiChain["Stateless Resource Server\n(KeycloakJwtAuthoritiesConverter)"]
    Match -->|"/web/**, /oauth2/** (@Order 2)"| WebChain["Stateful oauth2Login()\n(KeycloakOidcAuthoritiesMapper)"]
    ApiChain --> ApiRes["미인증 401 / 권한 매핑 후 인가"]
    WebChain --> WebRes["미인증 302 -> Keycloak Auth URL"]

웹 체인의 oauth2Login()은 JwtAuthenticationConverter를 거치지 않고 OidcUserAuthority를 생성합니다. 따라서 세션 기반 웹 요청에서도 동일한 ROLE_*과 Client Role을 쓰려면 GrantedAuthoritiesMapper 구현체를 별도로 연결해야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/main/java/com/example/keycloakdemo/security/KeycloakOidcAuthoritiesMapper.java
package com.example.keycloakdemo.security;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;

public class KeycloakOidcAuthoritiesMapper implements GrantedAuthoritiesMapper {

    private final String resourceClientId;

    public KeycloakOidcAuthoritiesMapper(String resourceClientId) {
        this.resourceClientId = resourceClientId;
    }

    @Override
    public Collection<? extends GrantedAuthority> mapAuthorities(
            Collection<? extends GrantedAuthority> authorities
    ) {
        Set<GrantedAuthority> mapped = new LinkedHashSet<>(authorities);

        for (GrantedAuthority authority : authorities) {
            if (authority instanceof OidcUserAuthority oidcAuthority) {
                extractFromClaims(oidcAuthority.getIdToken().getClaims(), mapped);
                if (oidcAuthority.getUserInfo() != null) {
                    extractFromClaims(oidcAuthority.getUserInfo().getClaims(), mapped);
                }
            }
        }
        return mapped;
    }

    @SuppressWarnings("unchecked")
    private void extractFromClaims(Map<String, Object> claims, Set<GrantedAuthority> target) {
        if (claims == null) {
            return;
        }
        Object realmAccess = claims.get("realm_access");
        if (realmAccess instanceof Map<?, ?> realmMap) {
            KeycloakJwtAuthoritiesConverter.extractRealmRoles((Map<String, Object>) realmMap, target);
        }
        Object resourceAccess = claims.get("resource_access");
        if (resourceAccess instanceof Map<?, ?> resourceMap) {
            KeycloakJwtAuthoritiesConverter.extractClientRoles(
                    (Map<String, Object>) resourceMap, resourceClientId, target);
        }
    }
}

이제 SecurityConfig에서 @Order(1) API 체인과 @Order(2) Web 체인을 각각 조립합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// src/main/java/com/example/keycloakdemo/security/SecurityConfig.java
package com.example.keycloakdemo.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Value("${app.security.resource-client-id:spring-api}")
    private String resourceClientId;

    @Bean
    public JwtAuthenticationConverter keycloakJwtAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(new KeycloakJwtAuthoritiesConverter(resourceClientId));
        converter.setPrincipalClaimName("preferred_username");
        return converter;
    }

    @Bean
    public GrantedAuthoritiesMapper keycloakOidcAuthoritiesMapper() {
        return new KeycloakOidcAuthoritiesMapper(resourceClientId);
    }

    @Bean
    @Order(1)
    public SecurityFilterChain apiSecurityFilterChain(
            HttpSecurity http,
            JwtAuthenticationConverter keycloakJwtAuthenticationConverter
    ) throws Exception {
        http
                .securityMatcher("/api/**")
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt.jwtAuthenticationConverter(keycloakJwtAuthenticationConverter))
                );
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain webSecurityFilterChain(
            HttpSecurity http,
            GrantedAuthoritiesMapper keycloakOidcAuthoritiesMapper
    ) throws Exception {
        http
                .securityMatcher("/web/**", "/login/**", "/oauth2/**", "/public/**")
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/public/**").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2Login(oauth2 -> oauth2
                        .userInfoEndpoint(userInfo -> userInfo
                                .userAuthoritiesMapper(keycloakOidcAuthoritiesMapper)
                        )
                );
        return http.build();
    }
}

컨트롤러는 @PreAuthorize로 Realm Role과 Client Role을 각각 검증합니다. (아래 /api/me는 핵심 로직만 발췌한 코드이며, 실제 테스트 응답에는 JwtAuthenticationToken에서 꺼낸 aud와 preferred_username 필드도 함께 포함했습니다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/main/java/com/example/keycloakdemo/web/DemoApiController.java
@RestController
@RequestMapping("/api")
public class DemoApiController {

    @GetMapping("/me")
    public Map<String, Object> me(Authentication authentication) {
        List<String> authorities = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .sorted()
                .toList();
        return Map.of("principal", authentication.getName(), "authorities", authorities);
    }

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public Map<String, Object> admin(Authentication authentication) {
        return Map.of("endpoint", "/api/admin", "user", authentication.getName());
    }

    @PostMapping("/orders")
    @PreAuthorize("hasAuthority('order:write')")
    public Map<String, Object> createOrder(Authentication authentication) {
        return Map.of("endpoint", "/api/orders", "status", "created", "user", authentication.getName());
    }
}

실제 실행과 테스트로 확인한 분기 결과

Keycloak 26.8.2 Docker 컨테이너(localhost:18280)와 Spring Boot 3.4.5 JAR(localhost:18281)를 함께 띄워 커스텀 컨버터 적용 결과와 멀티 체인 분기를 확인했습니다.

로컬 curl 검증에서는 CLI에서 토큰을 바로 발급받기 위해 테스트 클라이언트 spring-web에 directAccessGrantsEnabled: true(ROPC)를 임시로 켰습니다. 운영 환경에서는 ROPC를 사용하지 말고, OAuth 2.1과 RFC 9700 기준 PKCE(S256) 글에서 정리한 대로 Authorization Code + PKCE(S256) 흐름을 사용해야 합니다.

커스텀 KeycloakJwtAuthoritiesConverter를 활성화한 뒤 alice와 bob의 토큰으로 API를 호출한 결과입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--- GET /api/me (alice) ---
HTTP/1.1 200
{"principal":"alice","aud":["spring-api"],"authorities":["ROLE_ADMIN","ROLE_USER","SCOPE_email","SCOPE_openid","SCOPE_profile","order:read","order:write"],"preferred_username":"alice"}

--- GET /api/admin (alice) & POST /api/orders (alice) ---
HTTP/1.1 200  {"endpoint":"/api/admin","user":"alice"}
HTTP/1.1 200  {"status":"created","endpoint":"/api/orders","user":"alice"}

--- GET /api/me (bob) ---
HTTP/1.1 200
{"principal":"bob","aud":["spring-api"],"authorities":["ROLE_USER","SCOPE_email","SCOPE_openid","SCOPE_profile"],"preferred_username":"bob"}

--- GET /api/admin (bob) & POST /api/orders (bob) ---
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"

alice는 ROLE_ADMIN과 order:write가 정상 추출되어 두 엔드포인트 모두 200 OK를 받았고, resource_access: null인 bob은 NullPointerException 없이 /api/me 200 OK, /api/admin·/api/orders 403 Forbidden으로 정확히 분리됐습니다.

미인증 요청에 대한 멀티 SecurityFilterChain 분기도 의도대로 동작했습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
--- GET /api/me (unauthenticated) ---
HTTP/1.1 401
WWW-Authenticate: Bearer

--- GET /web/dashboard (unauthenticated) ---
HTTP/1.1 302
Set-Cookie: JSESSIONID=<MASKED_SESSION_ID>; Path=/; HttpOnly
Location: http://localhost:18281/oauth2/authorization/keycloak

--- GET /oauth2/authorization/keycloak ---
HTTP/1.1 302
Set-Cookie: JSESSIONID=<MASKED_SESSION_ID>; Path=/; HttpOnly
Location: http://localhost:18280/realms/demo-realm/protocol/openid-connect/auth?response_type=code&client_id=spring-web&scope=openid%20profile%20email&state=<MASKED_STATE>&redirect_uri=http://localhost:18281/login/oauth2/code/keycloak&nonce=<MASKED_NONCE>

/api/me는 세션을 만들지 않고 401 Unauthorized를 반환한 반면, /web/dashboard는 /oauth2/authorization/keycloak을 거쳐 Keycloak 26.8.2의 OIDC 인가 엔드포인트로 리다이렉트됐습니다.

이번 검증에서 oauth2Login()은 미인증 리다이렉트 진입(/web/dashboard → Keycloak Auth Endpoint)과 KeycloakOidcAuthoritiesMapper가 OidcUserAuthority에서 ROLE_ADMIN, ROLE_USER, order:write를 추출하는 JUnit 5·MockMvc 통합 테스트(5/5 통과)까지 확인했으며, 실제 브라우저 폼 로그인 후 콜백 코드 교환으로 /web/dashboard 200 OK를 받는 구간은 별도로 실행하지 않았습니다.

운영 적용 시 주의사항과 정리

실제 서비스에 이 구성을 옮길 때 놓치기 쉬운 지점은 네 가지입니다.

주의: JwtAuthenticationConverter 빈 자동 감지 Spring Security 6.4.5는 ApplicationContext에 JwtAuthenticationConverter 빈이 하나 등록되어 있으면, 다른 체인에서 oauth2.jwt(Customizer.withDefaults())를 호출해도 해당 빈을 자동으로 연결합니다. 체인별로 다른 컨버터를 써야 하거나 기본 동작을 유지할 체인이 있다면 전역 @Bean으로 노출하지 말고 체인 내부에서 직접 인스턴스를 주입하는 편이 안전합니다.

  1. aud 검증 누락 금지: spring.security.oauth2.resourceserver.jwt.audiences를 빼두면 같은 Realm의 다른 클라이언트용으로 발급된 Access Token도 이 API를 통과할 수 있습니다. Keycloak의 oidc-audience-mapper와 함께 반드시 짝지어 검증합니다.
  2. resource_access null 방어: Client Role이 없는 사용자는 Keycloak이 resource_access: null을 내려주거나 클레임 자체를 생략합니다. 컨버터와 매퍼 모두 null과 타입 검사를 포함해야 합니다.
  3. 웹 세션용 ID Token / UserInfo 매퍼 확인: KeycloakOidcAuthoritiesMapper는 Access Token이 아니라 OidcUserAuthority의 ID Token과 UserInfo 클레임을 읽습니다. 웹 체인에서 Role이 비어 있다면 Keycloak Client Scope의 roles 매퍼에서 Add to ID token 또는 Add to userinfo 옵션이 켜져 있는지 확인해야 합니다.
  4. 운영 인증 흐름 준수: 로컬 테스트용 ROPC(directAccessGrantsEnabled)는 운영 클라이언트에서 반드시 끄고, Authorization Code + PKCE(S256)만 허용하도록 제한합니다.

참고 자료

Most Resource Server support is collected into spring-security-oauth2-resource-server. However, the support for decoding and verifying JWTs is in spring-security-oauth2-jose, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens.
HttpSecurity.oauth2Login() provides a number of configuration options for customizing OAuth 2.0 Login. The main configuration options are grouped into their protocol endpoint counterparts.
The page you’re looking for does not exist.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.