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

8

可能我在这里做错了什么,我就是想不出来是什么...

我有一个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 未授权。

我该如何说服Spring Boot使/health可以匿名访问?


在 SecurityConfig 中,我认为您忘记添加以下内容:.antMatchers(HttpMethod.GET, "/health").permitAll(); - mherbert
1
你指定映射的顺序也是它们被查询的顺序。第一个匹配获胜...由于 /** 匹配所有内容,所以你的 /health 映射是无用的。将其移动到 /** 映射之上使其正常工作。 - M. Deinum
@M.Deinum 谢谢,问题已解决。如果您将此作为答案添加,我很乐意接受它。 - endrec
3个回答

4

我曾经也遇到过同样的问题,花了一些时间来解决。

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

仅仅这样还不够。

同时重写这个方法并添加以下内容,就可以实现了。

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

1
一整天都在做这个。找到了缺失的第二部分。谢谢。 - Chrispie

3
如M.Deinum所说: 指定映射的顺序也是它们被查询的顺序。第一个匹配胜出...由于/**可以匹配所有内容,因此你的/health映射是无用的。将其移到/**映射之前,使其正常工作。- M.Deinum于8月20日17:56发表评论。

0

2
此解决方案将禁用所有执行器端点的安全性。问题是如何允许匿名访问健康端点。 - quintonm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接