过滤器通过上一篇文章我们知道SecurityFilterChain决定了哪些请求通过过滤器链,那么SecurityFilterChain是如何匹配特定请求的呢?胖哥今天就为大家揭开这个秘密,希望各位同学能够点赞,再看,转发一波。如何拦截特定的请求只有满足SecurityFilterChain的match方法的请求才能被SecurityFilterChain处理,那么如何配置一个SecurityFilterChain来处理特定的路径呢?RequestMatcherHttpSecurity有一个内置的RequestMatcher属性来处理路径匹配问题。RequestMatcher可以归纳为以下几类:使用Ant路径:httpSecurity.antMatcher("/foo/**");如果配置了一个全局的ServletPath,比如/v1,那么配置ant路径为/v1/foo/**,使用MVC风格可以保持一致:httpSecurity.mvcMatcher("/foo/**");另外,MVC风格可以自动匹配后缀,比如/foo/hello可以匹配/foo/hello.do、/foo/hello.action等。另外,还可以使用正则表达式进行路径匹配:httpSecurity.regexMatcher("/foo/.+");如果以上都不能满足你的需求,你可以通过HttpSecurity.requestMatcher方法自定义匹配规则;如果你想匹配多个规则,可以使用HttpSecurity.requestMatchers方法自由组合匹配规则,像这样:httpSecurity.requestMatchers(requestMatchers->requestMatchers.mvcMatchers("/foo/**").antMatchers("/管理员/*获取"));一旦你配置了路径匹配规则,你会发现默认的formlogin是404,因为默认是/login,当然加上前缀后就不能访问了。使用场景比如你的后台管理系统和前端应用使用不同的过滤器链,你可以根据访问路径配置各自的过滤器链。例如:/***管理过滤器链。**@paramhttphttp*@return安全过滤器链*@throwsException异常*/@BeanSecurityFilterChainadminSecurityFilterChain(HttpSecurityhttp)throwsException{http.requestMatchers(requestMatchers->requestMatchers.mvcMatchers("/admin/**"))//todo其他配置returnhttp.build();}/***应用过滤器链。**@paramhttphttp*@return安全过滤器链*@throwsException异常*/@BeanSecurityFilterChainappSecurityFilterChain(HttpSecurityhttp)throwsException{http.requestMatchers(requestMatchers->requestMatchers.mvcMatchers("/app/**"));//todo其他配置returnhttp.build();另外,这个特性也可以用来降低不同正则URI之间的耦合度。想想为什么SpringBeanHttpSecurity可以复用。
