Apache Shiro 使用手冊(四) Realm 實現(xiàn)
在認證、授權內部實現(xiàn)機制中都有提到,最終處理都將交給Real進行處理。因為在Shiro中,最終是通過Realm來獲取應用程序中的用戶、角色及權限信息的。通常情況下,在Realm中會直接從我們的數(shù)據(jù)源中獲取Shiro需要的驗證信息??梢哉f,Realm是專用于安全框架的DAO.
一、認證實現(xiàn)
正如前文所提到的,Shiro的認證過程最終會交由Realm執(zhí)行,這時會調用Realm的getAuthenticationInfo(token)方法。
該方法主要執(zhí)行以下操作:
1、檢查提交的進行認證的令牌信息
2、根據(jù)令牌信息從數(shù)據(jù)源(通常為數(shù)據(jù)庫)中獲取用戶信息
3、對用戶信息進行匹配驗證。
4、驗證通過將返回一個封裝了用戶信息的AuthenticationInfo實例。
5、驗證失敗則拋出AuthenticationException異常信息。
而在我們的應用程序中要做的就是自定義一個Realm類,繼承AuthorizingRealm抽象類,重載doGetAuthenticationInfo (),重寫獲取用戶信息的方法。
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;
}
}
二、授權實現(xiàn)
而授權實現(xiàn)則與認證實現(xiàn)非常相似,在我們自定義的Realm中,重載doGetAuthorizationInfo()方法,重寫獲取用戶權限的方法即可。
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;
}
}
相關文章
使用CDN之后APACHE日志記錄中IP地址不正確的解決方案
這篇文章主要介紹了使用CDN之后APACHE日志記錄中IP地址不正確的解決方案,需要的朋友可以參考下2014-12-12關于安裝linux redhat后無法使用yum命令安裝gcc-c++問題的解決過程
這篇文章主要介紹了關于安裝linux redhat后無法使用yum命令安裝gcc-c++問題的解決過程,需要的朋友可以參考下2017-08-08