Spring Boot API与Actuator端点401未授权问题求助
解决Spring Boot Actuator端点返回401认证错误的问题
我来帮你搞定这个Actuator一直返回401的问题——我之前在Spring Boot 1.5.x版本里结合自定义Security配置时,也踩过一模一样的坑。核心问题是你自定义的WebSecurityConfigurerAdapter覆盖了Actuator的默认安全规则,哪怕你设置了management.security.enabled=false也没用,因为Spring Security的全局配置优先级更高。
问题出在哪?
看你的SecurityConfig代码,只给/users和/motion开了放行权限,但Actuator的端点(比如/health、/info这些)完全没被包含在规则里,所以Spring Security会默认拦截所有没明确放行的请求,要求认证。另外Spring Boot 1.5.x的Actuator端点默认都是/开头的,比如直接访问/health,这些路径不在你的antMatchers里,自然会返回401。
具体解决方案
只需要修改两个地方就行:
1. 更新SecurityConfig.java,放行Actuator端点
把Actuator的相关路径加入到antMatchers的放行列表里,代码改成这样:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 放行所有Actuator端点,包括子路径 .antMatchers("/actuator/**", "/health", "/info").permitAll() // 保留你原来的放行规则 .antMatchers("/users").permitAll() .antMatchers("/motion").permitAll() // 其他请求需要认证(如果不需要可以去掉这行) .anyRequest().authenticated() .and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
2. 优化application.properties配置
虽然management.security.enabled=false在1.5.x里可能被自定义Security覆盖,但加上下面的配置能确保Actuator的规则生效,还能按需暴露端点:
server.port=8080 spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/DevUserManagementDB spring.datasource.username=root spring.datasource.password=toor spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect # 禁用Actuator的安全验证 management.security.enabled=false # 暴露所有Actuator端点(如果只需要部分,改成逗号分隔的列表,比如health,info) management.endpoints.web.exposure.include=*
额外提醒
- 注意你的Spring Boot版本是1.5.9.RELEASE,这个版本的Actuator端点默认路径是
/health而不是/actuator/health(后者是2.x版本的默认路径),所以要把/health、/info这些也加进去放行。 - 你的
UserService实现了UserDetailsService,记得要确保loadUserByUsername方法能正确返回用户信息,虽然这不是当前401的直接原因,但后续如果需要认证功能的话,这个方法是核心。
改完之后重启服务,再访问Actuator端点应该就不会返回401了。
内容的提问来源于stack exchange,提问作者kaddie
相关产品推荐
相关产品推荐

