Spring Security Web : 概念模型接口 RequestMatcher

RequestMatcherSpring Security Web的一个概念模型接口,用于抽象建模对HttpServletRequest请求的匹配器这一概念。

RequestMatcher接口只定义了一个方法boolean matches(HttpServletRequest request),如果参数request和当前RequestMatcher实例匹配则返回true,从而达到判断是否某个请求是否匹配的目的。

源代码

源代码版本 : Spring Security Config 5.1.4.RELEASE

package org.springframework.security.web.util.matcher;

import javax.servlet.http.HttpServletRequest;

/**
 * Simple strategy to match an HttpServletRequest.
 *
 * @author Luke Taylor
 * @since 3.0.2
 */
public interface RequestMatcher {
     

	/**
	 * Decides whether the rule implemented by the strategy matches the supplied request.
	 *
	 * @param request the request to check for a match
	 * @return true if the request matches, false otherwise
	 */
	boolean matches(HttpServletRequest request);

}

Spring Security提供的RequestMatcher实现类

Spring Security内置提供了一些RequestMatcher实现类,框架需要用到RequestMatcher的地方,就会使用这些实现类。这些实现类位于包:
org.springframework.security.web.util.matcher

实现类 介绍
AnyRequestMatcher 匹配任何请求
AntPathRequestMatcher 使用ant风格的路径匹配模板匹配请求
ELRequestMatcher 使用EL表达式匹配请求
IpAddressMatcher 基于IP地址匹配请求,支持IPv4IPv6
MediaTypeRequestMatcher 基于MediaType匹配请求
RegexRequestMatcher 基于正则表达式匹配请求
RequestHeaderRequestMatcher 基于头部值比较匹配请求
AndRequestMatcher and组合多个RequestMatcher
OrRequestMatcher or组合多个RequestMatcher
NegatedRequestMatcher not操作一个RequestMatcher

另外在包org.springframework.security.web.servlet.util.matcher下面,Spring Security还提供了一个针对Spring MVC的请求匹配器:

实现类 介绍
MvcRequestMatcher 使用Spring MVCHandlerMappingIntrospector匹配请求

Spring SecurityRequestMatcher的使用

这里仅做举例说明。例子如下:

  • AntPathRequestMatcher的例子

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
     
    /**
     * @return
     */
    @Override
    public void configure(WebSecurity web) {
     
        // 静态资源文件对外公开,不需要访问授权
        // 此效果也可以通过 configure http 达到 : antMatchers("/static/**").permitAll()
        web.ignoring().antMatchers("/static/**");
    }
    
    
    // 省略其他代码
    // ...
 }    
  • RequestHeaderRequestMatcher的例子
public final class HttpBasicConfigurer<B extends HttpSecurityBuilder<B>> extends
		AbstractHttpConfigurer<HttpBasicConfigurer<B>, B> {
     

	private static final RequestHeaderRequestMatcher X_REQUESTED_WITH 
			= new RequestHeaderRequestMatcher("X-Requested-With","XMLHttpRequest");
// ...
}

这里web.ignoreing()实现类为 : WebSecurity$IgnoredRequestConfigurer,它继承自AbstractRequestMatcherRegistry

你可能感兴趣的:(Spring,Security,分析)