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

Spring Security权限异常:所有角色无法访问受保护端点

Spring Security角色权限不匹配导致端点无法访问的修复方案

问题根源

Spring Security的hasRole()方法会自动在角色名称前拼接ROLE_前缀做权限匹配,但你在配置用户权限时,直接用SimpleGrantedAuthority("ADMIN")和SimpleGrantedAuthority("CUSTOMER")定义角色,没有添加前缀,导致权限校验不通过,所有角色都无法访问目标端点。

两种修复方式(二选一即可)

方式一:给权限名称添加ROLE_前缀

修改用户权限配置,给角色名称加上ROLE_前缀:

@Bean
protected InMemoryUserDetailsManager configureAuthentication(){
    List<UserDetails> userDetails = new ArrayList<>();
    List<GrantedAuthority> customerRoles = new ArrayList<>();
    customerRoles.add(new SimpleGrantedAuthority("ROLE_CUSTOMER"));
    List<GrantedAuthority> adminRoles = new ArrayList<>();
    adminRoles.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

    userDetails.add(new User("user_customer", this.PasswordEncoder().encode("password"), customerRoles));
    userDetails.add(new User("user_admin", this.PasswordEncoder().encode("password"), adminRoles));
    return new InMemoryUserDetailsManager(userDetails);
}

方式二:用hasAuthority()替代hasRole()

如果不想手动加前缀,把权限校验方法换成hasAuthority(),它会直接匹配你配置的原始角色名称:

@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
    http
        .csrf().disable();
    http
        .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/api/v1/customers/", "/api/v1/customers").hasAuthority("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin();
    return http.build();
}

额外优化点

  1. 注意你的SecurityFilterChain配置中,.anyRequest().authenticated()后面多了一个冗余的点,需要删除,避免语法错误。
  2. 可以用User.withUsername()构建器简化用户创建,它会自动给roles()方法传入的名称添加ROLE_前缀:
@Bean
protected InMemoryUserDetailsManager configureAuthentication(){
    PasswordEncoder passwordEncoder = this.PasswordEncoder();
    List<UserDetails> userDetails = new ArrayList<>();
    
    userDetails.add(User.withUsername("user_customer")
            .password(passwordEncoder.encode("password"))
            .roles("CUSTOMER")
            .build());
    userDetails.add(User.withUsername("user_admin")
            .password(passwordEncoder.encode("password"))
            .roles("ADMIN")
            .build());
            
    return new InMemoryUserDetailsManager(userDetails);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:25:24