Shiro學習筆記(5)-Realm

前言

Realm在Shiro中充當獲取應用認證數據或者授權數據的角色,它可以訪問像數據庫、文件系統等等的數據存儲系統。可以把它理解成Shiro的‘DAO’層。

Realm配置

Realm可以在ini配置文件中進行聲明式的配置。如下:

fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm
bazRealm = com.company.baz.Realm

securityManager.realms = $fooRealm, $barRealm, $bazRealm

值得注意的是securityManager.realms中定義了Realm執行的順序。

Real 授權

AuthenticationTokens

在進行授權的流程中,Shiro最後會通過SecurityManager中的Authenticator 將AuthenticationToken傳遞給Realm,對Reaml來說認證分成了如下幾個主要的步驟。

  1. Realm會判斷傳入的AuthenticationToken是否支持認證。
  2. 檢查認證主體的token
  3. 基於主體查詢數據源中用戶的相關數據
  4. 確保token中提供的憑證(經常指密碼)和數據源中的匹配
  5. 如果匹配成功, 返回AuthenticationInfo(用來保存用戶的數據)
  6. 如果匹配失敗,拋出AuthenticationException異常

Credentials Matching(憑證配置)

Shiro默認使用的是SimpleCredentialsMatcher,如果想自定義Matcher,可以通過如下方式

Realm myRealm = new com.company.shiro.realm.MyRealm();
CredentialsMatcher customMatcher = new com.company.shiro.realm.CustomCredentialsMatcher();
myRealm.setCredentialsMatcher(customMatcher);

或者是

[main]
...
customMatcher = com.company.shiro.realm.CustomCredentialsMatcher
myRealm = com.company.shiro.realm.MyRealm
myRealm.credentialsMatcher = $customMatcher
...

Realm授權

基於角色的授權

  1. Subject會委派SecurityManager識別被賦予的角色
  2. SecurityManager委派Authorizer去檢查所有Authorizing Realm是否存在給定的角色。如果沒有符合的角色返回false
  3. 將所有角色賦值給主體
  4. 如果存在符合的角色,則放行

基於Permission的授權

  1. Subject委派給SecurityManager最終還是會委派給Authorizer
  2. Authorizer 通過通過查詢Realms來判斷是否符合權限

總結,Realm負責Shiro用戶的安全數據的查詢,並且負責對用戶進行最終的認證和授權工作。

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