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

Spring Security用户持对应角色仍返回403状态码问题解决

Spring Security 403权限拒绝问题解决方案

问题原因

Spring Security的hasRole()方法会自动为角色名称添加ROLE_前缀进行权限匹配,但你的Role枚举中getAuthority()方法直接返回枚举名(如USER),导致认证后的用户权限(USER)与配置中hasRole()期望的ROLE_USER不匹配,因此触发403拒绝访问。

从调试日志也能验证这一点:用户认证后Granted Authorities=[USER],但hasRole(Role.USER.getAuthority())实际在匹配ROLE_USER,两者不一致。

解决方案

方案一:修改Role枚举,添加ROLE_前缀

调整Role枚举的getAuthority()方法,返回带ROLE_前缀的权限字符串:

public enum Role implements GrantedAuthority {
    ADMIN,
    USER,
    MOD;

    @Override
    public String getAuthority() {
        return "ROLE_" + name();
    }
}

方案二:改用hasAuthority()方法匹配权限

在SecurityConfig中替换hasRole()为hasAuthority(),该方法不会自动添加前缀,直接匹配原始权限字符串:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .headers(x -> x.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/user/admin").hasAuthority(Role.ADMIN.getAuthority())
                    .requestMatchers("/user/mod").hasAuthority(Role.MOD.getAuthority())
                    .requestMatchers("/user/user").hasAuthority(Role.USER.getAuthority())
            )
            .formLogin(AbstractHttpConfigurer::disable)
            .httpBasic(Customizer.withDefaults()); 

    return http.build();
}

注:将多次authorizeHttpRequests调用合并为一次链式调用,是更规范的写法,效果与原代码一致但更简洁。

验证

修改后重新启动服务,使用对应角色用户访问端点,权限匹配即可正常返回200。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:35:54