【问题标题】:Spring Security antMatcher rule based on custom headers基于自定义标头的 Spring Security antMatcher 规则
【发布时间】:2019-11-15 06:25:03
【问题描述】:

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

.antMatchers( HttpMethod.POST, "/api/website-user" ).permitAll()

但是,我还有一些其他的“POST”方法也受到保护——对于这个特定的端点,我只希望通过发送的标头来识别和排除它。

你是怎么告诉 Spring 安全这个 URL 应该未经身份验证通过的

 @PostMapping( headers = "X-Operation-Name=forgot-password" )
   public WebsiteUser forgotPassword( @Valid PasswordResetRequestModel passwordReset )

但是例如这个不(并且依赖于经过身份验证的用户)?

@PostMapping( headers = "X-Operation-Name=resend-verification" )
   public WebsiteUser resendVerification( Principal principal )

【问题讨论】:

    标签: java spring spring-boot spring-security http-headers


    【解决方案1】:

    您始终可以实现 RequestMatcher 来定义您自定义的 HTTP 请求匹配逻辑。如果匹配器对 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,如RequestHeaderRequestMatcherAndRequestMatcher,应该适合你的需求:

    //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();
    

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 1970-01-01
      • 2022-09-23
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2016-06-23
      • 2021-04-21
      相关资源
      最近更新 更多