如何重新启用对 Spring Boot Health 端点的匿名访问?

How to re-enable anonymous access to Spring Boot Health endpoint?

可能我在这里做错了什么,我只是想不通是什么...

我在同一个应用程序中有一个 Oauth2 身份验证服务器和一个资源服务器。

资源服务器配置:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER-1)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    public static final String RESOURCE_ID = "resources";

    @Override
    public void configure(final ResourceServerSecurityConfigurer resources) {
        resources
                .resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/**").access("#oauth2.hasScope('read')")
                .antMatchers(HttpMethod.POST, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.PUT, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.PATCH, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.DELETE, "/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.GET, "/health").permitAll();
    }

}

认证服务器配置:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().httpBasic().realmName("OAuth Server");
    }
}

当我尝试访问 /health 时,我收到 HTTP/1.1 401 Unauthorized.

如何说服 Spring Boot 让 /health 匿名访问?

您还需要通过将 management.security.enabled 设置为 false 来禁用它。

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-customizing-management-server-port

正如 M. Deinum 所说:

The order in which you specify your mappings is also the order in which they are consulted. The first match wins... As /** matches everything your /health mapping is useless. Move that above the /** mappings to have it functional. – M. Deinum Aug 20 at 17:56

我遇到了同样的问题并且有点挣扎。

protected void configure(HttpSecurity http) throws Exception {
    ...
    .authorizeRequests()
            .antMatchers("/actuator/**").permitAll()
}

不够。

也重写此方法并添加以下内容即可。

public void configure(WebSecurity web) throws Exception {
     web.ignoring().antMatchers("/actuator/**");
}