Spring Security介绍(三)过滤器(1)过滤器链

Spring Security其实就是用filter,多请求的路径进行过滤,实现身份认证和授权。

Spring Security 在web场景的应用核心实现为Bean name为SpringSecurityFilterChain的这个Bean,Class为org.springframework.security.web.FilterChainProxy,SpringSecurityFilterChain中内部维护了一个FilterChain,默认FilterChain中会维护如下14个默认的Filter

其中有几个比较重要的过滤器:

FilterSecurityInterceptor、ExceptionTranslationFilter、UsernamePasswordAuthenticationFilter 。

一、CSRFFilter

1、介绍:

org.springframework.security.web.csrf.CsrfFilter#doFilterInternal

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        request.setAttribute(HttpServletResponse.class.getName(), response);
  			//从session中获取token
        CsrfToken csrfToken = this.tokenRepository.loadToken(request);
  			//token是否为空
        boolean missingToken = csrfToken == null;
        if (missingToken) {
          	//自动生成新的token
            csrfToken = this.tokenRepository.generateToken(request);
          	//保存token
            this.tokenRepository.saveToken(csrfToken, request, response);
        }

        request.setAttribute(CsrfToken.class.getName(), csrfToken);
        request.setAttribute(csrfToken.getParameterName(), csrfToken);
  			//是否是csrf需要校验的请求方式类型,默认TRACE,HEAD,GET,OPTIONS四种请求方式不校验
        if (!this.requireCsrfProtectionMatcher.matches(request)) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Did not protect against CSRF since request did not match " + this.requireCsrfProtectionMatcher);
            }
						//执行后续filter
            filterChain.doFilter(request, response);
        } else {
          	//否则需要校验,从请求头部获取token
            String actualToken = request.getHeader(csrfToken.getHeaderName());
            if (actualToken == null) {
              	//为空则从请求参数中获取
                actualToken = request.getParameter(csrfToken.getParameterName());
            }
						//判断两个token是否相等
            if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {
                this.logger.debug(LogMessage.of(() -> {
                    return "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request);
                }));
              	//token缺失或者不对应,对应两个异常类型
                AccessDeniedException exception = !missingToken ? new InvalidCsrfTokenException(csrfToken, actualToken) : new MissingCsrfTokenException(actualToken);
              	//交由accessDeniedHandler处理
                this.accessDeniedHandler.handle(request, response, (AccessDeniedException)exception);
            } else {
              	//相等继续执行后续Filter
                filterChain.doFilter(request, response);
            }
        }
    }
2、主要功能: 
21、

tokenRepository中获取token,默认是从HttpSessionCsrfTokenRepository即session中获取token;

2.2、

判断token是否为null,为null说明第一次请求,自动生成一个,并且设置到session

2.3、

判断是否是csrf需要校验的请求方式类型,默认TRACE,HEAD,GET,OPTIONS四种请求方式不校验

(1)不需要校验,直接执行后续FIlter

(2)需要校验:

从请求头中获取本次请求携带的token,没有则从请求参数中获取token
判断从session中获取的token和从请求头中获取的token是否一致
token一致,执行后续Filter
不一致
两个token都存在,但是校验失败,返回InvalidCsrfTokenException
否则返回MissingCsrfTokenException
上面生成的异常交由AccessDeniedHandler处理,最终返回处理的结果异常
3、使用:

如果开启了该功能,会对接口做拦截,返回Forbidden之类的内置错误提示。一般情况下关闭,正确的关闭方法:

 http.formLogin().and().authorizeRequests().anyRequest().authenticated().and().csrf().disable()

二、AccessDeniedHandler 

1、介绍

org.springframework.security.web.access.AccessDeniedHandlerImpl#handle


public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
  			//response是否已经提交
        if (response.isCommitted()) {
            logger.trace("Did not write to response since already committed");
        //异常页面配置是否为null
        } else if (this.errorPage == null) {
            logger.debug("Responding with 403 status code");
          	//为null则设置FORBIDDEN错误码
            response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
        } else {
            request.setAttribute("SPRING_SECURITY_403_EXCEPTION", accessDeniedException);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            if (logger.isDebugEnabled()) {
                logger.debug(LogMessage.format("Forwarding to %s with status code 403", this.errorPage));
            }
						//重定向到error页面
            request.getRequestDispatcher(this.errorPage).forward(request, response);
        }
    }
2、主要功能
  • 首先判断response是否已经提交,提交则什么也不做
  • 判断异常页面配置是否为null,为null则设置response的异常码
  • 异常页面不为null,则设置异常码,并且重定向到异常页面

三、UsernamePasswordAuthenticationFilter

1、介绍

对/login的POST请求做拦截,检查表单中的用户名和密码;

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
 }
2、条件

访问 /login 接口且为post请求才会进入这个过滤器。

3、认证流程
3.1、判断是否需要认证

如不需要认证,则直接执行下一个 Filter;如果需要认证,再向下继续进行。按照 Spring Security 框架的默认配置,此处只拦截 /login 且为post的请求,不会拦截其它请求。 

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
​
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
​
    if (!requiresAuthentication(request, response)) {
      chain.doFilter(request, response);
​
      return;
    }
protected boolean requiresAuthentication(HttpServletRequest request,
      HttpServletResponse response) {
    return requiresAuthenticationRequestMatcher.matches(request);
}
protected AbstractAuthenticationProcessingFilter(
      RequestMatcher requiresAuthenticationRequestMatcher) {
    Assert.notNull(requiresAuthenticationRequestMatcher,
                   "requiresAuthenticationRequestMatcher cannot be null");
    this.requiresAuthenticationRequestMatcher = requiresAuthenticationRequestMatcher;
}

同时,UsernamePasswordAuthenticationFilter 默认的无参构造方法,也对此进行了赋值(Ant风格路径匹配)

public UsernamePasswordAuthenticationFilter() {
    super(new AntPathRequestMatcher("/login", "POST"));
}

正是此处,默认了 /login(老版本为 /j_spring_security_check)为用户名密码验证路径,即 loginProcessingUrl(老版本为 filterProcessingUrl)。 

3.2、认证逻辑

具体的验证逻辑,在 UsernamePasswordAuthenticationFilter 中的 attemptAuthentication方法。

public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException(
            "Authentication method not supported: " + request.getMethod());
    }
​
    String username = obtainUsername(request);
    String password = obtainPassword(request);
​
    if (username == null) {
        username = "";
    }
​
    if (password == null) {
        password = "";
    }
​
    username = username.trim();
​
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
        username, password);
​
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
​
    return this.getAuthenticationManager().authenticate(authRequest);
}

attemptAuthentication 方法主要是搜集参数(username、password),封装为验证请求(UsernamePasswordAuthenticationToken),然后调用AuthenticationManager 进行身份认证,所以核心是AuthenticationManager.authenticate()。AuthenticationManager的认证逻辑见

Spring Security介绍(二)组件详解-CSDN博客

 这里我们只需要知道该过滤器是调用AuthenticationManager的认证方法实现的,而AuthenticationManager的认证方法会走到UserDetailsService接口的loadUserByUsername方法,所以使用UsernamePasswordAuthenticationFilter 的同时,需要自定义实现UserDetailsService。

3.3、认证成功和失败:

(1)成功:执行successfulAuthentication方法。

(2)失败:执行unsuccessfulAuthentication方法。

四、BasicAuthenticationFilter:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值