Spring Security常用过滤器实例解析

Spring Security常见的15个拦截器

1 . org.springframework.security.web.context.SecurityContextPersistenceFilter

首当其冲的一个过滤器,作用之重要,自不必多言。

  • SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存或更新一个
  • SecurityContext,并将SecurityContext给以后的过滤器使用,来为后续filter建立所需的上下文。
  • SecurityContext中存储了当前用户的认证以及权限信息。

2 . org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter

此过滤器用于集成SecurityContext到Spring异步执行机制中的WebAsyncManager

3 . org.springframework.security.web.header.HeaderWriterFilter

向请求的Header中添加相应的信息,可在http标签内部使用security:headers来控制

4 . org.springframework.security.web.csrf.CsrfFilter

csrf又称跨域请求伪造,SpringSecurity会对所有post请求验证是否包含系统生成的csrf的token信息,

如果不包含,则报错。起到防止csrf攻击的效果。

5. org.springframework.security.web.authentication.logout.LogoutFilter

匹配 URL为/logout的请求,实现用户退出,清除认证信息。

6 . org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

认证操作全靠这个过滤器,默认匹配URL为/login且必须为POST请求。

7 . org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter

如果没有在配置文件中指定认证页面,则由该过滤器生成一个默认认证页面。

8 . org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter

由此过滤器可以生产一个默认的退出登录页面

9 . org.springframework.security.web.authentication.www.BasicAuthenticationFilter

此过滤器会自动解析HTTP请求中头部名字为Authentication,且以Basic开头的头信息。

10 . org.springframework.security.web.savedrequest.RequestCacheAwareFilter

通过HttpSessionRequestCache内部维护了一个RequestCache,用于缓存HttpServletRequest

11 . org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter

针对ServletRequest进行了一次包装,使得request具有更加丰富的API

12 . org.springframework.security.web.authentication.AnonymousAuthenticationFilter

当SecurityContextHolder中认证信息为空,则会创建一个匿名用户存入到SecurityContextHolder中。

spring security为了兼容未登录的访问,也走了一套认证流程,只不过是一个匿名的身份。

13 . org.springframework.security.web.session.SessionManagementFilter

SecurityContextRepository限制同一用户开启多个会话的数量

14 . org.springframework.security.web.access.ExceptionTranslationFilter

异常转换过滤器位于整个springSecurityFilterChain的后方,用来转换整个链路中出现的异常

15 . org.springframework.security.web.access.intercept.FilterSecurityInterceptor

获取所配置资源访问的授权信息,根据SecurityContextHolder中存储的用户信息来决定其是否有权限。

那么,是不是spring security一共就这么多过滤器呢?答案是否定的!随着spring-security.xml配置的添加,还
会出现新的过滤器。

那么,是不是spring security每次都会加载这些过滤器呢?答案也是否定的!随着spring-security.xml配置的修
改,有些过滤器可能会被去掉。

spring security 过滤器链加载原理

public class DelegatingFilterProxy extends GenericFilterBean {
@Nullable
private String contextAttribute;
@Nullable
private WebApplicationContext webApplicationContext;
@Nullable
private String targetBeanName;
private boolean targetFilterLifecycle;
@Nullable
private volatile Filter delegate;//注:这个过滤器才是真正加载的过滤器
private final Object delegateMonitor;
//注:doFilter才是过滤器的入口,直接从这看!
public void doFilter(ServletRequest request, ServletResponse response, FilterChain
filterChain) throws ServletException, IOException {
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized(this.delegateMonitor) {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = this.findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no
ContextLoaderListener or DispatcherServlet registered?");
}
//第一步:doFilter中最重要的一步,初始化上面私有过滤器属性delegate
delegateToUse = this.initDelegate(wac);
}
this.delegate = delegateToUse;
}
}
//第三步:执行FilterChainProxy过滤器
this.invokeDelegate(delegateToUse, request, response, filterChain);
}
//第二步:直接看最终加载的过滤器到底是谁
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
//debug得知targetBeanName为:springSecurityFilterChain
String targetBeanName = this.getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
//debug得知delegate对象为:FilterChainProxy
Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class);
if (this.isTargetFilterLifecycle()) {
delegate.init(this.getFilterConfig());
}
return delegate;
}
protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse
response, FilterChain filterChain) throws ServletException, IOException {
delegate.doFilter(request, response, filterChain);
}
}

第二步debug结果如下:

由此可知, DelegatingFilterProxy通过springSecurityFilterChain这个名称,得到了一个FilterChainProxy过滤器,
最终在第三步执行了这个过滤器。

FilterChainProxy

public class FilterChainProxy extends GenericFilterBean {
private static final Log logger = LogFactory.getLog(FilterChainProxy.class);
private static final String FILTER_APPLIED =
FilterChainProxy.class.getName().concat(".APPLIED");
private List<SecurityFilterChain> filterChains;
private FilterChainProxy.FilterChainValidator filterChainValidator;
private HttpFirewall firewall;
//咿!?可以通过一个叫SecurityFilterChain的对象实例化出一个FilterChainProxy对象
//这FilterChainProxy又是何方神圣?会不会是真正的过滤器链对象呢?先留着这个疑问!
public FilterChainProxy(SecurityFilterChain chain) {
this(Arrays.asList(chain));
}
//又是SecurityFilterChain这家伙!嫌疑更大了!
public FilterChainProxy(List<SecurityFilterChain> filterChains) {
this.filterChainValidator = new FilterChainProxy.NullFilterChainValidator();
this.firewall = new StrictHttpFirewall();
this.filterChains = filterChains;
}
//注:直接从doFilter看
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
if (clearContext) {
try {
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
this.doFilterInternal(request, response, chain);
} finally {
SecurityContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
} else {
//第一步:具体操作调用下面的doFilterInternal方法了
this.doFilterInternal(request, response, chain);
}
}
private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
FirewalledRequest fwRequest =
this.firewall.getFirewalledRequest((HttpServletRequest)request);
HttpServletResponse fwResponse =
this.firewall.getFirewalledResponse((HttpServletResponse)response);
//第二步:封装要执行的过滤器链,那么多过滤器就在这里被封装进去了!
List<Filter> filters = this.getFilters((HttpServletRequest)fwRequest);
if (filters != null && filters.size() != 0) {
FilterChainProxy.VirtualFilterChain vfc = new
FilterChainProxy.VirtualFilterChain(fwRequest, chain, filters);
//第四步:加载过滤器链
vfc.doFilter(fwRequest, fwResponse);
} else {
if (logger.isDebugEnabled()) {
logger.debug(UrlUtils.buildRequestUrl(fwRequest) + (filters == null ? " has no
matching filters" : " has an empty filter list"));
}
fwRequest.reset();
chain.doFilter(fwRequest, fwResponse);
}
}
private List<Filter> getFilters(HttpServletRequest request) {
Iterator var2 = this.filterChains.iterator();
//第三步:封装过滤器链到SecurityFilterChain中!
SecurityFilterChain chain;
do {
if (!var2.hasNext()) {
return null;
}
chain = (SecurityFilterChain)var2.next();
} while(!chain.matches(request));
return chain.getFilters();
}
}

SecurityFilterChain

最后看SecurityFilterChain,这是个接口,实现类也只有一个,这才是web.xml中配置的过滤器链对象!

public interface SecurityFilterChain {
  boolean matches(HttpServletRequest request);
  List<Filter> getFilters();
}
public final class DefaultSecurityFilterChain implements SecurityFilterChain {
  private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
  private final RequestMatcher requestMatcher;
  private final List<Filter> filters;

  public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) {
    this(requestMatcher, Arrays.asList(filters));
  }

  public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {
    logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
    this.requestMatcher = requestMatcher;
    this.filters = new ArrayList<>(filters);
  }

  public RequestMatcher getRequestMatcher() {
    return requestMatcher;
  }

  public List<Filter> getFilters() {
    return filters;
  }

  public boolean matches(HttpServletRequest request) {
    return requestMatcher.matches(request);
  }

  @Override
  public String toString() {
    return "[ " + requestMatcher + ", " + filters + "]";
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringSecurity rememberme功能实现过程解析

    记住我功能原理分析 还记得前面咱们分析认证流程时,提到的记住我功能吗? 现在继续跟踪找到AbstractRememberMeServices对象的loginSuccess方法: 再点进去上面if判断中的rememberMeRequested方法,还在当前类中: 如果上面方法返回true,就表示页面勾选了记住我选项了. 继续顺着调用的方法找到PersistentTokenBasedRememberMeServices的onLoginSuccess方法: 注意name和value属性的值不要写错哦!

  • Spring security实现对账户进行加密

    一.原理分析1.1加密原理 首先前端页面发送注册的账户信息到controller层,然后依次经过service层和dao层,最后入库.其中对密码的加密应该放在service层进行,加密后再入库. spring security中有一个加密类BCryptPasswordEncoder可以用来对密码进行加密,调用其中的encode方法返回一个加密后的字符串 public String encode(CharSequence rawPassword) { String salt; if (streng

  • Spring Security和Shiro的相同点与不同点整理

    Spring Security和Shiro的区别 相同点 1.认证功能 2.授权功能 3.加密功能 4.会话管理 5.缓存支持 6.rememberMe功能 ... 不同点 1.Spring Security 基于Spring 开发,项目若使用 Spring 作为基础,配合 Spring Security 做权限更加方便,而 Shiro 需要和 Spring 进行整合开发: 2.Spring Security 功能比 Shiro 更加丰富些,例如安全维护方面: 3.Spring Security

  • Spring security BCryptPasswordEncoder密码验证原理详解

    一.加密算法和hash算法的区别 加密算法是一种可逆的算法,基本过程就是对原来为明文的文件或数据按某种算法进行处理,使其成为不可读的一段代码为"密文",但在用相应的密钥进行操作之后就可以得到原来的内容 . 哈希算法是一种不可逆的算法,是把任意长度的输入通过散列算法变换成固定长度的输出,输出就是散列值,不同的输入可能会散列成相同的输出,所以不可能从散列值来确定唯一的输入值. 二.源码解析 BCryptPasswordEncoder类实现了PasswordEncoder接口,这个接口中定义

  • SpringSecurity的防Csrf攻击实现代码解析

    CSRF(Cross-site request forgery)跨站请求伪造,也被称为One Click Attack或者Session Riding,通常缩写为CSRF或XSRF,是一种对网站的恶意利用.尽管听起来像跨站脚本(XSS),但它与XSS非常不同,XSS利用站点内的信任用户,而CSRF则通过伪装成受信任用户的请求来利用受信任的网站.与XSS攻击相比,CSRF攻击往往不大流行(因此对其进行防范的资源也相当稀少)和难以防范,所以被认为比XSS更具危险性. CSRF是一种依赖web浏览器的

  • 详解Spring Security认证流程

    前言 Spring Seuciry相关的内容看了实在是太多了,但总觉得还是理解地不够巩固,还是需要靠知识输出做巩固. 相关版本: java: jdk 8 spring-boot: 2.1.6.RELEASE 过滤器链和认证过程 一个认证过程,其实就是过滤器链上的一个绿色矩形Filter所要执行的过程. 基本的认证过程有三步骤: Filter拦截请求,生成一个未认证的Authentication,交由AuthenticationManager进行认证: AuthenticationManager的

  • SpringSecurity权限控制实现原理解析

    菜单控制: 可以用来判断这个用户是不是有这些角色,没有的话就不展示 数据控制: 由于数据都是从后端查的,在后端控制权限就可以了 <!-- 开启权限控制注解支持 jsr250-annotations="enabled"表示支持jsr250-api的注解,需要jsr250-api的jar包 pre-post-annotations="enabled"表示支持spring表达式注解 secured-annotations="enabled"这才是

  • Spring Security使用数据库认证及用户密码加密和解密功能

    流程图: 1.接上一篇博客https://mp.csdn.net/console/editor/html/104576494,准备好环境. 2.spring-security.xml中的配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="

  • Spring Security常用过滤器实例解析

    Spring Security常见的15个拦截器 1 . org.springframework.security.web.context.SecurityContextPersistenceFilter 首当其冲的一个过滤器,作用之重要,自不必多言. SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存或更新一个 SecurityContext,并将SecurityContext给以后的过滤器使用,来

  • Spring Security CsrfFilter过滤器用法实例

    这篇文章主要介绍了Spring Security CsrfFilter过滤器用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 spring security框架提供的默认登录页面,会有一个name属性值为_csrf的隐藏域: 这是框架在用户访问登录页面之前就生成的,保存在内存中,当用户提交表单的时候会跟着一起提交:_csrf_formdata 然后会经过spring security框架resources目录下配置文件spring-sec

  • Spring security 自定义过滤器实现Json参数传递并兼容表单参数(实例代码)

    依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId&g

  • spring学习之@SessionAttributes实例解析

    本文研究的主要是spring学习之@SessionAttributes的相关内容,具体如下. 一.@ModelAttribute 在默认情况下,ModelMap 中的属性作用域是 request 级别是,也就是说,当本次请求结束后,ModelMap中的属性将销毁.如果希望在多个请求中共享 ModelMap 中的属性,必须将其属性转存到 session 中,这样ModelMap 的属性才可以被跨请求访问. spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session

  • Spring Cloud Feign组件实例解析

    这篇文章主要介绍了Spring Cloud Feign组件实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 采用Spring Cloud微服务框架后,经常会涉及到服务间调用,服务间调用采用了Feign组件. 由于之前有使用dubbo经验.dubbo的负载均衡策略(轮训.最小连接数.随机轮训.加权轮训),dubbo失败策略(快速失败.失败重试等等), 所以Feign负载均衡策略的是什么? 失败后是否会重试,重试策略又是什么?带这个疑问,查了

  • Python列表切片常用操作实例解析

    这篇文章主要介绍了Python列表切片常用操作实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 最近在爬一个网站的文档的时候,老师要求把一段文字切割开来,根据中间的文本分成两段 故学习了一段时间的切片操作,现把学习成果po上来与大家分享 1.何为切片? 列表的切片就是处理列表中的部分元素,是把整个列表切开的方法. 切片可以说是整个列表中的重点内容,相信你在以后的Python项目中会经常使用到. 它的语法是: 2.简单介绍切片的几个常见操作

  • java泛型常用通配符实例解析

    这篇文章主要介绍了java泛型常用通配符实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 今天在看ArrayList原码是看到这样的一个符号,好奇怪. ?表示通配符,表示的意思是匹配E或E的子类,具体类型未知. 1.限定通配符 编写一个类似于ArrayList的动态数据 public class Gys<T> { private final static int default_capacity =10; private int end

  • Spring Security基于过滤器实现图形验证码功能

    目录 前言 一. 验证码简介 二. 基于过滤器实现图形验证码 1. 实现概述 2. 创建新模块 3. 添加依赖包 4. 创建Producer对象 5. 创建生成验证码的接口 6. 自定义异常 7. 创建拦截验证码的过滤器 8. 编写SecurityConfig 9. 编写测试页面 10. 代码结构 11. 启动项目测试 前言 在前两个章节中,一一哥 带大家学习了Spring Security内部关于认证授权的核心API,以及认证授权的执行流程和底层原理.掌握了这些之后,对于Spring Secu

  • Spring Security的过滤器链机制

    目录 前言 请求执行链路 推荐阅读 前言 在“码农小胖哥”的文章中提到一个关键的过滤器链SecurityFilterChain,当一个请求 HttpServletRequest 进入 SecurityFilterChain 时,会通过 matches 方法来确定是否满足条件进入过滤器链,进而决定请求应该执行哪些过滤器.下面我们自己来梳理一遍. 请求执行链路 我们以之前的文章为例,使用@Configuration配置了一个SecurityFilterChain Bean,能在Spring Boot

  • Spring Security 核心过滤器链讲解

    目录 一.Filter Chain 图解 二.过滤器逐一解析 2.1.WebAsyncManagerIntegrationFilter 2.2.SecurityContextPersistenceFilter 2.3.HeaderWriterFilter 2.4.CsrfFilter 2.5.LogoutFilter 2.6.RequestCacheAwareFilter 2.7.SecurityContextHolderAwareRequestFilter 2.8.AnonymousAuthe

随机推荐