【问题标题】:Spring Security Custom Header Request Matcher Not WorkingSpring Security 自定义标头请求匹配器不工作
【发布时间】:2021-09-09 14:50:39
【问题描述】:

我有一个使用spring security的要求,如果任何类型的请求包含具有特定值的特定标头,那么只有它应该被允许访问api,否则不允许。下面是我的配置代码:

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter{

    public AppSecurityConfig() {
    }
    
    @Autowired
    public void configure​(HttpSecurity http) throws Exception {
    http.authorizeRequests().requestMatchers(new CustomHeaderRequestMatcher()).permitAll();
    
    }

}

下面是customer header request matcher业务逻辑:

public class CustomHeaderRequestMatcher implements RequestMatcher{

    public CustomHeaderRequestMatcher() {
    
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        if(Objects.nonNull(request.getHeader("my-token"))
                && request.getHeader("my-token").equals("abc")) {
            System.out.println("true");
            return true;
        }
        System.out.println("false");
        return false;
    }

}

但是在这里我可以看到,即使我没有在我的请求中传递自定义标头“my-token”,它也允许访问 api。对于每个请求,尽管正在调用自定义请求匹配器类。我很困惑为什么 spring security 不处理这个案子?

【问题讨论】:

  • 您尚未阻止所有其他请求。 spring 看到了第一条规则,不知道接下来要做什么。您可以在“permitAll()”之后添加“anyRequest().denyAll()”或“anyRequest().authenticated()”
  • 谢谢,是的,正如你所说,我没有处理未发送请求标头的负面情况,然后如何处理这些请求:)

标签: java spring-boot spring-security


【解决方案1】:

您尚未阻止所有其他请求。 spring 看到了第一条规则,不知道接下来要做什么。您可以在“permitAll()”之后添加“anyRequest().denyAll()”或“anyRequest().authenticated()”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2019-01-01
    • 2020-07-10
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多