You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security解析含scp前缀的JWT时Scope为空,如何自定义解析?

解决Spring Security解析JWT时识别scp作为Scope别名的问题

可以通过自定义JWT认证转换器,指定Spring Security使用scp字段作为Scope的来源,具体步骤如下:

1. 自定义JwtAuthenticationConverter

创建自定义转换器,配置JwtGrantedAuthoritiesConverter以识别scp字段:

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

public class CustomJwtAuthenticationConverter extends JwtAuthenticationConverter {

    public CustomJwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
        // 将scope字段指定为JWT中的"scp"
        authoritiesConverter.setScopeAttributeName("scp");
        // 可选:修改权限前缀,默认是"SCOPE_",如果不需要可以设为空字符串
        // authoritiesConverter.setAuthorityPrefix("");
        setJwtGrantedAuthoritiesConverter(authoritiesConverter);
    }
}

2. 在资源服务器配置中使用自定义转换器

修改Spring Security配置,让OAuth2资源服务器使用这个自定义转换器解析JWT:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(new CustomJwtAuthenticationConverter())
                )
            );
        return http.build();
    }
}

补充说明

  • 不管JWT中的scp是单个字符串(如"scp": "read_notifications.v1")还是数组格式(如"scp": ["read", "write"]),转换器都能自动解析并生成对应的GrantedAuthority。
  • 默认生成的权限会带上SCOPE_前缀,如果不需要这个前缀,取消注释代码中的setAuthorityPrefix("")即可。

内容的提问来源于stack exchange,提问作者Timothy Vogel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 23:35:02