shiro登錄認證過程講解


 

 

先粘出登錄的代碼

1.

 

可以看到已經獲取到了username和password ,為了接下來的認證過程,我們需要獲取subject對象,也就是代表當前登錄用戶,並且要將username和password兩個變量設置到UsernamePasswordToken對象的token中, 調用SecurityUtils.getSubject().login(token)方法,將 token傳入

接下來看看login方法的實現:

主要還是用到了securityManager安全管理器

進入securityManager里邊的login方法,看看他的實現:

 在這個方法中定義了AuthenticationInfo對象來接受從Realm傳來的認證信息

進入authenticate方法中

 

發現調用了authenticator的authenticate這個方法

進入this.authenticator.authenticate(token)這個方法中

在這個 類中調用了這個方法,再進去看他的實現

  1.  
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
  2.  
    this.assertRealmsConfigured();
  3.  
    Collection<Realm> realms = this.getRealms();
  4.  
    return realms.size() == 1?this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken):this.doMultiRealmAuthentication(realms, authenticationToken);
  5.  
    }

在這里才是剛才前邊的那個authenticator的實現, this.assertRealmsConfigured() 這個方法是判斷realm是否存在,不存在則拋出異常,他會根據realm的個數來判斷執行哪個方法,上篇中springboot整合shiro我只配置了一個realm,所以他只會執行this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken)這個方法,並且會將 realm和token作為參數傳入,這里的realm其實就是自己定義的MyShiroRealm

接下來再進入doSingleRealmAuthentication這個方法中,

在這里 他會先判斷realm是否支持token

接下來執行else中的getAuthenticationInfo方法

this.getCachedAuthenticationInfo(token)這個方法是從shiro緩存中讀取用戶信息,如果沒有,才從realm中獲取信息。如果是第一次登陸,緩存中肯定沒有認證信息,所以會執行this.doGetAuthenticationInfo(token)這個方法。

查看this.doGetAuthenticationInfo(token)方法,會發現有這么幾個類提供我們選擇

其中就有我們自定義的realm,進去

 所以 ,上邊的doGetAuthorizationInfo是 執行的我們自定義realm中重寫的doGetAuthorizationInfo這個方法。這個方法就會從數據庫中讀取我們所需要的信息,最后封裝成SimpleAuthorizationInfo返回去。

現在獲取到認證信息了,接下來就是shiro怎么去進行認證,我們返回去看

 獲取 完信息之后就是進行密碼匹配,進入assertCredentialsMatch方法中看一下,

首先 獲取一個CredentialsMatcher對象,譯為憑證匹配器,這個類的主要作用就是將用戶輸入的密碼一某種計算加密。

再看一下cm.doCredentialsMatch(token,info)

這里會用到equals方法對token中加密的密碼和從數據庫中取出來的info中的密碼進行對比,如果認證相同就返回true,失敗就返回false,並拋出AuthenticationException,將info返回到defaultSecurityManager中,到此認證過程結束。

 

原文鏈接:https://blog.csdn.net/caoyang0105/article/details/82769293


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM