[Java] Spring Security登陆流程讲解

2022-08-19 | 500 人阅读

本文主要介绍了Spring Security登陆流程讲解,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在Spring Security中,认证授权都是通过过滤器来实现的。
当开始登陆的时候,有一个关键的过滤器UsernamePasswordAuthenticationFilter,该类继承抽象类AbstractAuthenticationProcessingFilter,在AbstractAuthenticationProcessingFilter里有一个doFilter方法,一切先从这里说起。
  1. private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
  2.       throws IOException, ServletException {
  3.    if (!requiresAuthentication(request, response)) {
  4.       chain.doFilter(request, response);
  5.       return;
  6.    }
  7.    try {
  8.       Authentication authenticationResult = attemptAuthentication(request, response);
  9.       if (authenticationResult == null) {
  10.          // return immediately as subclass has indicated that it hasn't completed
  11.          return;
  12.       }
  13.       this.sessionStrategy.onAuthentication(authenticationResult, request, response);
  14.       // Authentication success
  15.       if (this.continueChainBeforeSuccessfulAuthentication) {
  16.          chain.doFilter(request, response);
  17.       }
  18.       successfulAuthentication(request, response, chain, authenticationResult);
  19.    }
  20.    catch (InternalAuthenticationServiceException failed) {
  21.       this.logger.error("An internal error occurred while trying to authenticate the user.", failed);
  22.       unsuccessfulAuthentication(request, response, failed);
  23.    }
  24.    catch (AuthenticationException ex) {
  25.       // Authentication failed
  26.       unsuccessfulAuthentication(request, response, ex);
  27.    }
  28. }
复制代码
首先requiresAuthentication先判断是否尝试校验,通过后调用attemptAuthentication方法,这个方法也就是UsernamePasswordAuthenticationFilter 中的attemptAuthentication方法。
  1. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  2.       throws AuthenticationException {
  3.    if (this.postOnly && !request.getMethod().equals("POST")) {
  4.       throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  5.    }
  6.    String username = obtainUsername(request);
  7.    username = (username != null) ? username : "";
  8.    username = username.trim();
  9.    String password = obtainPassword(request);
  10.    password = (password != null) ? password : "";
  11.    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  12.    // Allow subclasses to set the "details" property
  13.    setDetails(request, authRequest);
  14.    return this.getAuthenticationManager().authenticate(authRequest);
  15. }
复制代码
1.在UsernamePasswordAuthenticationFilter 的attemptAuthentication方法中,先是验证请求的类型,是否是POST请求,如果不是的话,抛出异常。(PS:登陆肯定要用POST方法了)
2.然后拿到username和password。这里使用的是obtainUsername方法,也就是get方法。
  1. @Nullable
  2. protected String obtainPassword(HttpServletRequest request) {
  3.    return request.getParameter(this.passwordParameter);
  4. }
  5. @Nullable
  6. protected String obtainUsername(HttpServletRequest request) {
  7.    return request.getParameter(this.usernameParameter);
  8. }
复制代码
由此我们知道了Spring Security中是通过get方法来拿到参数,所以在进行前后端分离的时候是无法接受JSON数据,处理方法就是自定义一个Filter来继承UsernamePasswordAuthenticationFilter,重写attemptAuthentication方法,然后创建一个Filter实例写好登陆成功和失败的逻辑处理,在HttpSecurity参数的configure中通过addFilterAt来替换Spring Security官方提供的过滤器。
3.创建一个UsernamePasswordAuthenticationToken 实例。
4.设置Details,在这里关键的是在WebAuthenticationDetails类中记录了用户的remoteAddress和sessionId。
  1. public WebAuthenticationDetails(HttpServletRequest request) {
  2.    this.remoteAddress = request.getRemoteAddr();
  3.    HttpSession session = request.getSession(false);
  4.    this.sessionId = (session != null) ? session.getId() : null;
  5. }
复制代码
5.拿到一个AuthenticationManager通过authenticate方法进行校验,这里以实现类ProviderManager为例。
  1. @Override
  2. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  3.    //获取Authentication的运行时类
  4.    Class<? extends Authentication> toTest = authentication.getClass();
  5.    AuthenticationException lastException = null;
  6.    AuthenticationException parentException = null;
  7.    Authentication result = null;
  8.    Authentication parentResult = null;
  9.    int currentPosition = 0;
  10.    int size = this.providers.size();
  11.    
  12.    for (AuthenticationProvider provider : getProviders()) {
  13.        //判断是否支持处理该类别的provider
  14.       if (!provider.supports(toTest)) {
  15.          continue;
  16.       }
  17.       if (logger.isTraceEnabled()) {
  18.          logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)",
  19.                provider.getClass().getSimpleName(), ++currentPosition, size));
  20.       }
  21.       try {
  22.           //获取用户的信息
  23.          result = provider.authenticate(authentication);
  24.          if (result != null) {
  25.             copyDetails(authentication, result);
  26.             break;
  27.          }
  28.       }
  29.       catch (AccountStatusException | InternalAuthenticationServiceException ex) {
  30.          prepareException(ex, authentication);
  31.          // SEC-546: Avoid polling additional providers if auth failure is due to
  32.          // invalid account status
  33.          throw ex;
  34.       }
  35.       catch (AuthenticationException ex) {
  36.          lastException = ex;
  37.       }
  38.    }
  39.    //不支持的话跳出循环再次执行
  40.    if (result == null && this.parent != null) {
  41.       // Allow the parent to try.
  42.       try {
  43.          parentResult = this.parent.authenticate(authentication);
  44.          result = parentResult;
  45.       }
  46.       catch (ProviderNotFoundException ex) {
  47.          // ignore as we will throw below if no other exception occurred prior to
  48.          // calling parent and the parent
  49.          // may throw ProviderNotFound even though a provider in the child already
  50.          // handled the request
  51.       }
  52.       catch (AuthenticationException ex) {
  53.          parentException = ex;
  54.          lastException = ex;
  55.       }
  56.    }
  57.    if (result != null) {
  58.        //擦除用户的凭证 也就是密码
  59.       if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
  60.          // Authentication is complete. Remove credentials and other secret data
  61.          // from authentication
  62.          ((CredentialsContainer) result).eraseCredentials();
  63.       }
  64.       // If the parent AuthenticationManager was attempted and successful then it
  65.       // will publish an AuthenticationSuccessEvent
  66.       // This check prevents a duplicate AuthenticationSuccessEvent if the parent
  67.       // AuthenticationManager already published it
  68.       if (parentResult == null) {
  69.           //公示登陆成功
  70.          this.eventPublisher.publishAuthenticationSuccess(result);
  71.       }
  72.       return result;
  73.    }
  74.    // Parent was null, or didn't authenticate (or throw an exception).
  75.    if (lastException == null) {
  76.       lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",
  77.             new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}"));
  78.    }
  79.    // If the parent AuthenticationManager was attempted and failed then it will
  80.    // publish an AbstractAuthenticationFailureEvent
  81.    // This check prevents a duplicate AbstractAuthenticationFailureEvent if the
  82.    // parent AuthenticationManager already published it
  83.    if (parentException == null) {
  84.       prepareException(lastException, authentication);
  85.    }
  86.    throw lastException;
  87. }
复制代码
6.经过一系列校验,此时登陆校验基本完成,当验证通过后会执行doFilter中的successfulAuthentication方法,跳转到我们设置的登陆成功界面,验证失败会执行unsuccessfulAuthentication方法,跳转到我们设置的登陆失败界面。
到此这篇关于Spring Security登陆流程讲解的文章就介绍到这了,更多相关Spring Security登陆内容请搜索OPEN开发家园以前的文章或继续浏览下面的相关文章希望大家以后多多支持OPEN开发家园
原文链接:https://blog.csdn.net/MAKEJAVAMAN/article/details/121021287

[occ]文档来源:网络转载 http://www.zzvips.com/article/231024.html[/occ]
关注下面的标签,发现更多相似文章
3253 积分
3251 主题
OPNE在线字典
热门推荐