繁体   English   中英

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

[英]Spring Security antMatcher rule based on custom headers

在Spring框架内,我目前正在尝试使用自定义标头而非url来区分某些端点。 目前,我似乎看不到如何使用自定义标头来允许特定的URL,但是在Spring Security中拒绝另一个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 )

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

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

您始终可以实现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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM