You need to enable JavaScript to run this app. Spring Security配置普通用户与管理员权限后接口持续返回401未授权
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security配置普通用户与管理员权限后接口持续返回401未授权

401异常核心定位

日志明确提示DaoAuthenticationProvider找不到admin用户、抛出BadCredentialsException,说明请求还未进入密码校验环节,问题根因是自定义的内存认证配置未实际生效,而非接口权限规则或请求头传参错误。

排查&解决步骤
  • 确认自定义安全配置类的加载状态
    • 检查类是否同时标注@Configuration、@EnableWebSecurity两个注解,缺少任意一个Spring都不会加载该配置逻辑
    • 检查类的包路径是否在Spring Boot主类(标注@SpringBootApplication的类)的默认扫描范围内:若配置类和主类不在同一层级包下,需给主类添加@SpringBootApplication(scanBasePackages = "你的根包路径"),否则配置类无法被扫描加载,会触发Spring Boot默认的安全配置(自动生成随机密码的默认user账号)
    • 检查项目内是否存在多个继承WebSecurityConfigurerAdapter的配置类,若存在需给每个类标注@Order(整数)指定优先级,避免低优先级配置覆盖自定义的内存认证配置
  • 校验内存用户配置的代码逻辑
    • 必须通过重写configure(AuthenticationManagerBuilder auth)方法注册内存用户,禁止将用户配置写在configure(HttpSecurity http)的接口权限配置块中
    • 检查链式调用是否存在拼写错误:比如用户名是否写对、是否漏了.roles()的绑定
    • 确认Basic认证请求头里传入的用户名、密码大小写和配置完全一致,Spring Security默认对用户名做大小写敏感匹配
    • 密码前的{noop}标识不能省略:若省略该标识,Spring Security会尝试用默认的BCryptPasswordEncoder校验明文密码,会直接抛出异常
  • 参考可正常运行的配置示例
@Configuration
@EnableWebSecurity
public class PersonSecurityConfig extends WebSecurityConfigurerAdapter {

    // 注册内存认证账号
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }

    // 配置接口权限规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/persons/all").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/persons/create").hasRole("USER")
                .antMatchers(HttpMethod.DELETE, "/persons/delete/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.PUT, "/persons/update/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().disable()
                .csrf().disable();
    }
}
生效验证方法

启动项目后观察启动日志:

  • 若日志打印Using generated security password: 随机字符串,说明自定义配置未生效,回到第一部分排查加载问题
  • 若日志无上述默认密码打印,可使用curl命令测试:
    curl -u admin:password http://你的服务地址/persons/all
    可正常返回结果即代表配置生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 12:36:08