小编典典

Spring Boot 2:如果附加了Authorization标头,则基本Http Auth会导致不受保护的端点以401“ Unauthorized”响应

spring-boot

迁移到Spring Boot 2并为执行器和另一个控制端点的应用程序添加基本授权要求之后,就不可能用Authorization标头调用任何不受保护的端点了。

配置代码段:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}

例如,使用“ Authorization:Basic …”对… / health进行调用将导致401“未授权”,即使不受Spring安全保护。

问题: 如何调整配置,以便可以将带有“授权”标头的请求发送到任何不受保护的端点而不会被拒绝?

UPD: 此修复程序如我所愿

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .antMatchers("/payment/**").permitAll()
            .and().httpBasic();
}

UPD2: 没关系,刚刚测试了另一个请求,仍然收到401“未经授权”。

curl localhost:8080/payment/<any_endpoint> -H "Authorization: Basic asdadas"
{"code":401,"message":"Unauthorized"}

不幸的是,这种方法会覆盖HttpSecurity匹配器,例如:/ payment /变得可访问

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("shutdown")).fullyAuthenticated()
            .antMatchers("/payment/status/*").fullyAuthenticated()
            .and().httpBasic();
}

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring().antMatchers("/payment/**");
}

UPD 3: 我创建了一个简单的项目,并复制了此问题
https://github.com/Anoobizzz/SpringSecurity2BasicAuthDemo

  1. / internal和/ shutdown仅可通过以下用户访问:P455W0RD
  2. /暴露无权访问
  3. /暴露于标头“ Authorization:Basic 123123”,并返回401“ Unauthorized”

阅读 887

收藏
2020-05-30

共1个答案

小编典典

通过调用.authorizeRequests(),您可以强制所有这些请求的授权,因为您尚未调用.ignore()某个匹配器。

我建议ignore**匹配器上使用,然后在允许所有层的顶部对指定的匹配器逐步执行授权,以便可以访问除明确指定的对象之外的所有内容。

这可以完成您想要做的事情,但是请注意,这不是最佳实践,有很好的理由:默认情况下,您应拒绝所有未经授权的流量,并且仅明确允许对特定路由模板的未经授权的请求。

就是说,明智的做法是ignore,在不需要身份验证的情况下仅在希望访问的路由上明确使用,而不仅仅是**(例如仅针对/home - /about - /login - /signup

2020-05-30