Java 基于自定义头的Spring Security antMatcher规则

Java 基于自定义头的Spring Security antMatcher规则,java,spring,spring-boot,spring-security,http-headers,Java,Spring,Spring Boot,Spring Security,Http Headers,在Spring框架中,我目前正在尝试使用自定义头而不是URL来区分一些端点。目前,我似乎不知道如何允许一个带有自定义头的特定URL,但在SpringSecurity中拒绝另一个URL。我的安全配置当前有一个antMatcher,如下所示: .antMatchers( HttpMethod.POST, "/api/website-user" ).permitAll() 然而,我还有一些其他的“POST”方法也受到保护——对于这个特定的端点,我只希望通过发送的头来识别和排除它 你是如何告诉Spri

在Spring框架中,我目前正在尝试使用自定义头而不是URL来区分一些端点。目前,我似乎不知道如何允许一个带有自定义头的特定URL,但在SpringSecurity中拒绝另一个URL。我的安全配置当前有一个antMatcher,如下所示:

.antMatchers( HttpMethod.POST, "/api/website-user" ).permitAll()
然而,我还有一些其他的“POST”方法也受到保护——对于这个特定的端点,我只希望通过发送的头来识别和排除它

你是如何告诉Spring安全部门这个URL应该通过未经验证的方式传递的

 @PostMapping( headers = "X-Operation-Name=forgot-password" )
   public WebsiteUser forgotPassword( @Valid PasswordResetRequestModel passwordReset )
但是这个例子不需要(并且依赖于经过身份验证的用户)


您始终可以实现一个
RequestMatcher
来定义定制的HTTP请求匹配逻辑。如果matcher为HTTP请求返回true,它将允许该请求访问:

public MyRequestMatcher implements RequestMatcher {

    boolean matches(HttpServletRequest request){
         //Define the matching logic here....
         if(request.getHeader("xxx") != null &&
            request.getHeader("xxx").equals("yyyy"){
             return true;
         }
         //blablablab
    }
} 
要配置使用此匹配器,请执行以下操作:

 httpSecurity.authorizeRequests().requestMatchers(new MyRequestMatcher()).permitAll();
Spring Security还提供一些常见的
RequestMatcher
,如
requestheaderrrequestmatcher
AndRequestMatcher
,它们应该适合您的需要:

//This matches if the request has X-Operation-Name header and its value is forgot-password
RequestHeaderRequestMatcher headerMatcher = new RequestHeaderRequestMatcher("X-Operation-Name","forgot-password" );

// This matches if the request is POST to the /api/website-user
AntPathRequestMatcher antRequestMatcher = new AntPathRequestMatcher("/api/website-user", HttpMethod.POST)

// This matches if both of the above matches matches 
AndRequestMatcher andMatcher = new AndRequestMatcher(headerMatcher,antRequestMatcher );

httpSecurity.authorizeRequests().requestMatchers(andMatcher).permitAll();
//This matches if the request has X-Operation-Name header and its value is forgot-password
RequestHeaderRequestMatcher headerMatcher = new RequestHeaderRequestMatcher("X-Operation-Name","forgot-password" );

// This matches if the request is POST to the /api/website-user
AntPathRequestMatcher antRequestMatcher = new AntPathRequestMatcher("/api/website-user", HttpMethod.POST)

// This matches if both of the above matches matches 
AndRequestMatcher andMatcher = new AndRequestMatcher(headerMatcher,antRequestMatcher );

httpSecurity.authorizeRequests().requestMatchers(andMatcher).permitAll();