HttpSecurity实际上就是在配置Spring security的过滤器链,比如:CSRF,CORS,表单登录等,每个配置器对应一个过滤器,可以通过HttpSecurity配置过滤器的行为。
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous().disable().authorizeRequests().
antMatchers("/echo/**") // 访问资源
.access("hasRole('ADMIN')") // 访问资源所需要的权限;
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
甚至可以像CRSF一样直接关闭过滤器,例如:SessionManagement
public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception{
return (SessionManagementConfigurer) this.getOrApply(new SessionManagementConfig());
Spring Security通过SessionManagermentConfigurer来配置SessionManagerment的行为,与SessionManagermentConfigurer类似的配置器还有CorsConfigurer,RememberMeConfigurer等,他们都实现了SecurityConfigurer的标准接口。
public interface SecurityConfigurer<O,B extends SecurityBuilder<O>>{
// 各个配置器的初始化方法
void init(B var1) throws Exception;
// 各个配置器被统一调用的配置方法
void configurer(B var1) throws Exception;
SessionManagementConfigurer是在configure方法中将最终的SessionManagementFilter插入过滤器链来实现会话管理的。
public void configure(H http){
SecurityContextRepository securityContextRepository = (SecurityContextRepository) http.getSharedObject(SecurityContextRepository.class);
// 初始化 SessionManagementFilter
SessionManagementFilter sessionManagementFilter = new SessionManagermentFilter(securityContextRepository,this.getSessionAuthenticationStartegy(http));
if(this.sessionAuthenticationErrorUrl != null){
sessionManagementFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(this.sessionAuthenticationErrorUrl));
InvalidSessionStrategy strategy = this.getInvalidSessionStrategy();
if(strategy != null ){
sessionManagementFilter.setInvalidSessionStrategy(strategy);
AuthenticationFailureHandler failureHandler = this.getSessionAuthenticationFailureHandler();
if(failureHandler != null){
sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
AuthenticationTrustResolver = trustResolver = (AuthenticationTrustResolver) http.getShareObject(AuthenticationTrustResolver.class);
if(trustResolver != null ){
sessionManagementFilter.setTrustResolver(trustResolver);
sessionManagementFilter = (SessionManageFilter)this.postProcess(sessionManagementFilter);
// 将SessionManagementFilter 添加到过滤器上
http.addFilter(sessionManagementFilter);
if(this.isConcurrentSessionControlEnabled()){
ConcurrentSessionFilter concurrentSessionFilter = this.createConcurencyFilter(http);
concurrentSessionFilter = (ConcurrentSessionFilter)this.postProcess(concurrentSessionFilter);
http.addFilter(concurrentSessionFilter);
除了Spring security提供的过滤器外,我们还可以添加自己的过滤器以实现更多的功能,这些都是可以在HttpSecurity中实现
// 将自定义的过滤器添加在指定过滤器之后
public HttpSecurity addFilterAfter(Filter filter,Class<? extends Filter> after){
this.comparator.registerAfter(filter.getClass(),afterFilter);
return this.addFilter(filter);
// 将自定义过滤器添加在指定过滤器之前
public HttpSecurity addFilterBefore(Filter filter,Class<? extends Filter> beforeFilter){
this.comparator.registerBefore(filter.getClass(),beforeFilter);
return this.addFilter(filter);
// 添加一个过滤器,但必须是Spring Security自身提供的过滤器实例或者继承过滤器,详情见FilterComparator类
public HttpSecurity addFilter(Filter){
Class<? extends Filter> filterClass = filter.getClass();
if(!this.comparator.isRegistered(filterClass)){
throw new IllegalArgumentException(....);
}else{
this.filters.add(filter);
return this;
// 添加一个自定义过滤器在指定过滤器位置
public HttpSecurity addFilterAt(Filter filter,Class<? extends Filter> atFilter){
this.comparator.registerAt(filter.getClass(),atFilter);
return this.addFilter(filter);
虽然Spring Security 的过滤器链对过滤器没有特殊要求,只要继承了Filter即可,但是在Spring体系中,推荐使用OnePerRequestFilter来实现,它可以确保一次请求只会通过一次该过滤器(Filter实际并不能保证这一点)
其实关于这个自定义Filter,我个人感觉有个比较danteng的地方,比如:我们在实现图片验证码或者一些其他的登录相关的验证码的时候,我们可能会做到在账号跟密码验证了之后对这个验证码进行验证,然后我就必须有个这种操作: http.addFilterBefore(filter,UsernamePasswordAuthenticationFilter.class); 因为如果验证码验证错误,我们就不需要也没必要再往后验证了,所以我们得知道我们定义的这个验证码过滤器得在什么时候验证在哪个过滤器之前或者之后验证,那么问题来了,或许我们并不知道Spring Security给我们提供了哪些或者什么样的过滤器,我们得去记住这些过滤器,这就有点不友好了。在HttpSecurityBuilder接口中,有一段这样的注释:
* <li>{@link ChannelProcessingFilter}</li>
* <li>{@link ConcurrentSessionFilter}</li>
* <li>{@link SecurityContextPersistenceFilter}</li>
* <li>{@link LogoutFilter}</li>
* <li>{@link X509AuthenticationFilter}</li>
* <li>{@link AbstractPreAuthenticatedProcessingFilter}</li>
* <li><a href="{@docRoot}/org/springframework/security/cas/web/CasAuthenticationFilter.html">CasAuthenticationFilter</a></li>
* <li>{@link UsernamePasswordAuthenticationFilter}</li>
* <li>{@link ConcurrentSessionFilter}</li>
* <li>{@link OpenIDAuthenticationFilter}</li>
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter}</li>
* <li>{@link org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter}</li>
* <li>{@link ConcurrentSessionFilter}</li>
* <li>{@link DigestAuthenticationFilter}</li>
* <li>{@link org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter}</li>
* <li>{@link BasicAuthenticationFilter}</li>
* <li>{@link RequestCacheAwareFilter}</li>
* <li>{@link SecurityContextHolderAwareRequestFilter}</li>
* <li>{@link JaasApiIntegrationFilter}</li>
* <li>{@link RememberMeAuthenticationFilter}</li>
* <li>{@link AnonymousAuthenticationFilter}</li>
* <li>{@link SessionManagementFilter}</li>
* <li>{@link ExceptionTranslationFilter}</li>