最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security登陸流程講解

 更新時間:2021年11月04日 14:01:13   作者:Java Gosling  
本文主要介紹了Spring Security登陸流程講解,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

在Spring Security中,認證授權都是通過過濾器來實現(xiàn)的。

當開始登陸的時候,有一個關鍵的過濾器UsernamePasswordAuthenticationFilter,該類繼承抽象類AbstractAuthenticationProcessingFilter,在AbstractAuthenticationProcessingFilter里有一個doFilter方法,一切先從這里說起。

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
   if (!requiresAuthentication(request, response)) {
      chain.doFilter(request, response);
      return;
   }
   try {
      Authentication authenticationResult = attemptAuthentication(request, response);
      if (authenticationResult == null) {
         // return immediately as subclass has indicated that it hasn't completed
         return;
      }
      this.sessionStrategy.onAuthentication(authenticationResult, request, response);
      // Authentication success
      if (this.continueChainBeforeSuccessfulAuthentication) {
         chain.doFilter(request, response);
      }
      successfulAuthentication(request, response, chain, authenticationResult);
   }
   catch (InternalAuthenticationServiceException failed) {
      this.logger.error("An internal error occurred while trying to authenticate the user.", failed);
      unsuccessfulAuthentication(request, response, failed);
   }
   catch (AuthenticationException ex) {
      // Authentication failed
      unsuccessfulAuthentication(request, response, ex);
   }
}

首先requiresAuthentication先判斷是否嘗試校驗,通過后調(diào)用attemptAuthentication方法,這個方法也就是UsernamePasswordAuthenticationFilter 中的attemptAuthentication方法。

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

1.在UsernamePasswordAuthenticationFilter 的attemptAuthentication方法中,先是驗證請求的類型,是否是POST請求,如果不是的話,拋出異常。(PS:登陸肯定要用POST方法了)
2.然后拿到username和password。這里使用的是obtainUsername方法,也就是get方法。

@Nullable
protected String obtainPassword(HttpServletRequest request) {
   return request.getParameter(this.passwordParameter);
}

@Nullable
protected String obtainUsername(HttpServletRequest request) {
   return request.getParameter(this.usernameParameter);
}

由此我們知道了Spring Security中是通過get方法來拿到參數(shù),所以在進行前后端分離的時候是無法接受JSON數(shù)據(jù),處理方法就是自定義一個Filter來繼承UsernamePasswordAuthenticationFilter,重寫attemptAuthentication方法,然后創(chuàng)建一個Filter實例寫好登陸成功和失敗的邏輯處理,在HttpSecurity參數(shù)的configure中通過addFilterAt來替換Spring Security官方提供的過濾器。
3.創(chuàng)建一個UsernamePasswordAuthenticationToken 實例。
4.設置Details,在這里關鍵的是在WebAuthenticationDetails類中記錄了用戶的remoteAddress和sessionId。

public WebAuthenticationDetails(HttpServletRequest request) {
   this.remoteAddress = request.getRemoteAddr();
   HttpSession session = request.getSession(false);
   this.sessionId = (session != null) ? session.getId() : null;
}

5.拿到一個AuthenticationManager通過authenticate方法進行校驗,這里以實現(xiàn)類ProviderManager為例。

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
   //獲取Authentication的運行時類
   Class<? extends Authentication> toTest = authentication.getClass();
   AuthenticationException lastException = null;
   AuthenticationException parentException = null;
   Authentication result = null;
   Authentication parentResult = null;
   int currentPosition = 0;
   int size = this.providers.size();
   
   for (AuthenticationProvider provider : getProviders()) {
       //判斷是否支持處理該類別的provider
      if (!provider.supports(toTest)) {
         continue;
      }
      if (logger.isTraceEnabled()) {
         logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)",
               provider.getClass().getSimpleName(), ++currentPosition, size));
      }
      try {
          //獲取用戶的信息
         result = provider.authenticate(authentication);
         if (result != null) {
            copyDetails(authentication, result);
            break;
         }
      }
      catch (AccountStatusException | InternalAuthenticationServiceException ex) {
         prepareException(ex, authentication);
         // SEC-546: Avoid polling additional providers if auth failure is due to
         // invalid account status
         throw ex;
      }
      catch (AuthenticationException ex) {
         lastException = ex;
      }
   }
   //不支持的話跳出循環(huán)再次執(zhí)行
   if (result == null && this.parent != null) {
      // Allow the parent to try.
      try {
         parentResult = this.parent.authenticate(authentication);
         result = parentResult;
      }
      catch (ProviderNotFoundException ex) {
         // ignore as we will throw below if no other exception occurred prior to
         // calling parent and the parent
         // may throw ProviderNotFound even though a provider in the child already
         // handled the request
      }
      catch (AuthenticationException ex) {
         parentException = ex;
         lastException = ex;
      }
   }
   if (result != null) {
       //擦除用戶的憑證 也就是密碼
      if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) {
         // Authentication is complete. Remove credentials and other secret data
         // from authentication
         ((CredentialsContainer) result).eraseCredentials();
      }
      // If the parent AuthenticationManager was attempted and successful then it
      // will publish an AuthenticationSuccessEvent
      // This check prevents a duplicate AuthenticationSuccessEvent if the parent
      // AuthenticationManager already published it
      if (parentResult == null) {
          //公示登陸成功
         this.eventPublisher.publishAuthenticationSuccess(result);
      }

      return result;
   }

   // Parent was null, or didn't authenticate (or throw an exception).
   if (lastException == null) {
      lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",
            new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}"));
   }
   // If the parent AuthenticationManager was attempted and failed then it will
   // publish an AbstractAuthenticationFailureEvent
   // This check prevents a duplicate AbstractAuthenticationFailureEvent if the
   // parent AuthenticationManager already published it
   if (parentException == null) {
      prepareException(lastException, authentication);
   }
   throw lastException;
}

 6.經(jīng)過一系列校驗,此時登陸校驗基本完成,當驗證通過后會執(zhí)行doFilter中的successfulAuthentication方法,跳轉(zhuǎn)到我們設置的登陸成功界面,驗證失敗會執(zhí)行unsuccessfulAuthentication方法,跳轉(zhuǎn)到我們設置的登陸失敗界面。

到此這篇關于Spring Security登陸流程講解的文章就介紹到這了,更多相關Spring Security登陸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • SpringBoot項目nohup啟動運行日志過大的解決方案

    SpringBoot項目nohup啟動運行日志過大的解決方案

    這篇文章主要介紹了SpringBoot項目nohup啟動運行日志過大的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Java ExecutorServic線程池異步實現(xiàn)流程

    Java ExecutorServic線程池異步實現(xiàn)流程

    這篇文章主要介紹了Java ExecutorServic線程池異步實現(xiàn)流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12
  • java隨機字符補充版

    java隨機字符補充版

    今天在zuidaimai看到一個java隨機字符生成demo,正好要用,但發(fā)現(xiàn)不完整,重新整理一下,分享給有需要的朋友
    2014-01-01
  • MacOS如何安裝配置多個JDK并切換使用詳解

    MacOS如何安裝配置多個JDK并切換使用詳解

    這篇文章主要介紹了如何在MacOS上安裝和配置多個JDK版本,通過配置環(huán)境變量來實現(xiàn),文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-02-02
  • 詳解slf4j+logback在java工程中的配置

    詳解slf4j+logback在java工程中的配置

    這篇文章主要介紹了slf4j+logback在java工程中的配置,對日志組件logback也進行了簡單介紹,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2015-08-08
  • Java實現(xiàn)將導出帶格式的Excel數(shù)據(jù)到Word表格

    Java實現(xiàn)將導出帶格式的Excel數(shù)據(jù)到Word表格

    在Word中制作報表時,我們經(jīng)常需要將Excel中的數(shù)據(jù)復制粘貼到Word中,這樣則可以直接在Word文檔中查看數(shù)據(jù)而無需打開另一個Excel文件。本文將通過Java應用程序詳細介紹如何把帶格式的Excel數(shù)據(jù)導入Word表格。希望這篇文章能對大家有所幫助
    2022-11-11
  • SpringCloud feign微服務調(diào)用之間的異常處理方式

    SpringCloud feign微服務調(diào)用之間的異常處理方式

    這篇文章主要介紹了SpringCloud feign微服務調(diào)用之間的異常處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • nacos單機本地配置文件存儲位置方式

    nacos單機本地配置文件存儲位置方式

    這篇文章主要介紹了nacos單機本地配置文件存儲位置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Java為何需要平衡方法調(diào)用與內(nèi)聯(lián)

    Java為何需要平衡方法調(diào)用與內(nèi)聯(lián)

    這篇文章主要介紹了Java為何需要平衡方法調(diào)用與內(nèi)聯(lián),幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2021-01-01
  • javaWeb如何實現(xiàn)隨機圖片驗證碼詳解

    javaWeb如何實現(xiàn)隨機圖片驗證碼詳解

    這篇文章主要給大家介紹了關于javaWeb如何實現(xiàn)隨機圖片驗證碼的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03

最新評論

繁峙县| 昌图县| 拜泉县| 绥中县| 四平市| 宜君县| 和平县| 和平县| 文化| 靖州| 敦煌市| 射洪县| 高碑店市| 莱阳市| 福清市| 玉田县| 云梦县| 玉龙| 祁门县| 田阳县| 华宁县| 汪清县| 赤壁市| 开远市| 泾源县| 杭州市| 敦化市| 郑州市| 虎林市| 嘉荫县| 鄂托克前旗| 突泉县| 湾仔区| 凤凰县| 宁都县| 延吉市| 武强县| 睢宁县| 庆阳市| 临桂县| 沂南县|