You need to enable JavaScript to run this app. Spring Boot如何移除hasAuthority的SCOPE_前缀并配置ScopeVoter
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何移除hasAuthority的SCOPE_前缀并配置ScopeVoter

自定义Scope前缀配置方案

核心根因

Spring Security 默认在解析JWT/Opaque Token的scope声明时,会自动为每个scope值拼接默认前缀SCOPE_生成权限条目;同时内置的ScopeVoter投票器在校验权限时,也会使用相同的默认前缀做匹配。两边前缀不统一就会出现裸scope值校验失败的问题。

具体配置步骤

1. 自定义ScopeVoter实例

直接在Spring容器中注册自定义配置的ScopeVoterBean,调用setScopePrefix方法传入目标前缀即可:

@Bean
public ScopeVoter customScopeVoter() {
    ScopeVoter voter = new ScopeVoter();
    // 传入空字符串即可实现无固定前缀,直接匹配裸scope值
    voter.setScopePrefix("");
    return voter;
}

2. 把自定义ScopeVoter接入安全决策链

将自定义投票器加入HTTP安全配置的访问决策器列表,覆盖默认的ScopeVoter:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ScopeVoter customScopeVoter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<AccessDecisionVoter<?>> voters = new ArrayList<>();
        // 保留Spring Security默认的核心投票器
        voters.add(new RoleVoter());
        voters.add(new AuthenticatedVoter());
        // 加入自定义的ScopeVoter
        voters.add(customScopeVoter);
        
        http
            .authorizeRequests()
            .accessDecisionManager(new AffirmativeBased(voters))
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer();
    }
}

3. 同步修改Token解析的权限生成规则

仅修改投票器前缀无法生效,必须同步调整Token解析时的权限生成逻辑,让生成的权限条目和ScopeVoter的前缀规则匹配:
如果是Spring Security 5.x+ 原生JWT资源服务配置:

@Bean
public JwtDecoder jwtDecoder() {
    NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation("你的认证服务根地址");
    // 自定义权限转换逻辑,直接从scope声明生成无权限前缀的GrantedAuthority
    decoder.setClaimSetConverter((jwt) -> {
        Set<GrantedAuthority> authorities = new HashSet<>();
        String scopeClaim = jwt.getClaimAsString("scope");
        if (StringUtils.hasText(scopeClaim)) {
            Arrays.stream(scopeClaim.split(" "))
                .filter(StringUtils::hasText)
                .forEach(scope -> authorities.add(new SimpleGrantedAuthority(scope.trim())));
        }
        return authorities;
    });
    return decoder;
}

如果是旧版Spring Security OAuth2 2.x 版本:

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setVerifierKey("你的认证服务公钥");
    // 覆盖默认的权限生成逻辑,去掉自动拼接的SCOPE_前缀
    converter.setAccessTokenConverter(new DefaultAccessTokenConverter() {
        @Override
        public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
            OAuth2Authentication originalAuth = super.extractAuthentication(map);
            List<GrantedAuthority> strippedAuthorities = originalAuth.getAuthorities().stream()
                .map(auth -> new SimpleGrantedAuthority(auth.getAuthority().replace("SCOPE_", "")))
                .collect(Collectors.toList());
            return new OAuth2Authentication(originalAuth.getOAuth2Request(), originalAuth.getUserAuthentication()) {
                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    return strippedAuthorities;
                }
            };
        }
    });
    return converter;
}

4. 方法级安全适配

如果项目开启了方法级权限校验,需要同步调整表达式处理器的默认前缀,保证@PreAuthorize注解的校验逻辑和全局规则一致:

@Configuration
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        OAuth2MethodSecurityExpressionHandler handler = new OAuth2MethodSecurityExpressionHandler();
        // 前缀值必须和ScopeVoter中设置的值保持一致
        handler.setDefaultRolePrefix("");
        return handler;
    }
}

注意事项

  • 配置完成后,原有的hasAuthority('SCOPE_phone')写法会因为权限前缀不匹配失效,需要统一改成对应规则的写法;如果需要兼容两种写法,可以在生成权限条目时同时保留带SCOPE_前缀和不带前缀的两份权限。
  • 修改前缀时不要改动角色校验的默认ROLE_前缀规则,否则会导致接口角色权限校验逻辑异常。

内容的提问来源于stack exchange,提问作者Loi Nguyen Tri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 17:06:07