一、認證實現
正如前文所提到的,Shiro的認證過程最終會交由Realm執行,這時會調用Realm的getAuthenticationInfo(token)方法。
該方法主要執行以下操作:
1、檢查提交的進行認證的令牌信息
2、根據令牌信息從數據源(通常爲數據庫)中獲取用戶信息
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;
- }
- }
二、授權實現
而授權實現則與認證實現非常相似,在我們自定義的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;
- }
- }
原文鏈接:http://kdboy.iteye.com/blog/1169631