Apache Shiro 使用手冊(四)Realm 實現

來源:互聯網
上載者:User

標籤:9.png   account   筆記   資訊   apache   技術   gpe   驗證   simple   

在認證、授權內部實現機制中都有提到,最終處理都將交給Real進行處理。因為在Shiro中,最終是通過Realm來擷取應用程式中的使用者、角色及許可權資訊的。通常情況下,在Realm中會直接從我們的資料來源中擷取Shiro需要的驗證資訊。可以說,Realm是專用於安全架構的DAO。 

一、認證實現 
正如前文所提到的,Shiro的認證過程最終會交由Realm執行,這時會調用Realm的getAuthenticationInfo(token)方法。 
該方法主要執行以下操作:
1、檢查提交的進行認證的令牌資訊 
2、根據令牌資訊從資料來源(通常為資料庫)中擷取使用者資訊 
3、對使用者資訊進行匹配驗證
4、驗證通過將返回一個封裝了使用者資訊的AuthenticationInfo執行個體
5、驗證失敗則拋出AuthenticationException異常資訊

而在我們的應用程式中要做的就是自訂一個Realm類,繼承AuthorizingRealm抽象類別,重載doGetAuthenticationInfo (),重寫擷取使用者資訊的方法。 
Java代碼  
  1. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
  2.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
  3.         User user = accountManager.findUserByUserName(token.getUsername());  
  4.         if (user != null) {  
  5.             return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());  
  6.         } else {  
  7.             return null;  
  8.         }  
  9. }  

二、授權實現 
而授權實現則與認證實現非常相似,在我們自訂的Realm中,重載doGetAuthorizationInfo()方法,重寫擷取使用者權限的方法即可。 
Java代碼  
  1. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  2.         String userName = (String) principals.fromRealm(getName()).iterator().next();  
  3.         User user = accountManager.findUserByUserName(userName);  
  4.         if (user != null) {  
  5.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  6.             for (Group group : user.getGroupList()) {  
  7.                 info.addStringPermissions(group.getPermissionList());  
  8.             }  
  9.             return info;  
  10.         } else {  
  11.             return null;  
  12.         }  
  13. }  


來源: http://kdboy.iteye.com/blog/1169631

來自為知筆記(Wiz)

Apache Shiro 使用手冊(四)Realm 實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.