安全框架Shiro——Shiro認證、授權流程

在這裏插入圖片描述

一、認證的流程

  1. 獲取當前的Subject, 調用SecurityUtils.getSubject();
  2. 測試當前用戶是否已經被認證, 即是否已經登錄, 調用Subject的isAuthentication()
  3. 若沒有被認證, 則把用戶名和密碼封裝爲UsernamePasswordToken對象
    • 創建一個表單頁面
    • 把請求提交到Controller中
    • 獲取用戶名和密碼
  4. 前臺執行登錄, 調用Subject的login(AuthenticationToken)方法
  5. 自定義Realm, 從數據庫中獲取對應的記錄, 返回給Shiro
    • 自定義的Realm需要繼承org.apache.shiro.realm.AuthorizingRealm
    • 實現protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)方法
    • 實現方法中的參數就是前臺中login方法中的token
  6. 由shiro內部自動完成密碼的比對

二、認證實現

Controller
在這裏插入圖片描述
實現doGetAuthenticationInfo方法

// 認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("執行了->認證UserRealm.doGetAuthenticationInfo");
    
    // 1. 把AuthenticationToken 轉爲 UsernamePasswordToken
    UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

    // 2. 從數據庫中獲取用戶: userToken.getUsername()就是前臺用戶輸入的用戶名
    User user = userService.queryUserByName(userToken.getUsername());

    // 3. 用戶不存在, 拋出異常
    if (user == null) {
        return null; // 拋出異常 UnknowAccountException
    }

    // 4. 根據用戶的情況,來構建 AuthenticationInfo對象並返回,常常使用SimpleAuthenticationInfo
    // arg1: principal: 認證的實體信息,可以是username,也可以是數據表中對應用戶的實體類
    // arg2: credentials: 密碼,shiro底層自動幫我們做比對了
    // arg3: realName: 當前realm對象的name, 調用父類的getName()即可
    return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}
  • 在Controller中封裝的token(封裝了用戶的信息), 爲什麼和我們重寫的doGetAuthenticationInfo方法參數是同一個對象;

首先從Controller中subject.login(token)的login方法點進去一直找(如下圖)

在這裏插入圖片描述
找到AuthenticatingRealm類中的方法, 其中就調用了我們重寫的doGetAuthenticationInfo(token)方法, 即將用戶封裝的信息傳遞了過去!
在這裏插入圖片描述

三、shiro鹽值加密md5

在這裏插入圖片描述

在這裏插入圖片描述

四、授權

在這裏插入圖片描述
授權流程

  1. 自定義的Realm繼承AuthorizingRealm類實現protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)方法

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章