標籤: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代碼
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
- UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
- User user = accountManager.findUserByUserName(token.getUsername());
- if (user != null) {
- return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
- } else {
- return null;
- }
- }
二、授權實現
而授權實現則與認證實現非常相似,在我們自訂的Realm中,重載doGetAuthorizationInfo()方法,重寫擷取使用者權限的方法即可。
Java代碼
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- String userName = (String) principals.fromRealm(getName()).iterator().next();
- User user = accountManager.findUserByUserName(userName);
- if (user != null) {
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- for (Group group : user.getGroupList()) {
- info.addStringPermissions(group.getPermissionList());
- }
- return info;
- } else {
- return null;
- }
- }
來源: http://kdboy.iteye.com/blog/1169631
來自為知筆記(Wiz)
Apache Shiro 使用手冊(四)Realm 實現