Realm: 域,Shiro從Realm獲取安全數據(如用戶、角色、權限),就是說SecurityManager要驗證用戶身份,那麼它需要從Realm獲取相應的用戶進行以確定用戶身份是否合法,也需要從Realm得到用戶相應的角色權限進行驗證用戶是否能進行操作。
自定義Realm
繼承AuthorizingRealm實現我們自己的Realm類
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
String username = (String) token.getPrincipal();
User user = new User();
user.setUsername(username);
user.setPassword("123456");
if (!"itmyhome".equals(username)) {
// 拋出 帳號找不到異常
throw new UnknownAccountException();
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getUsername(), // 用戶名
user.getPassword(), // 密碼
getName() // realm name
);
return authenticationInfo;
}
}
ini配置文件指定自定義Realm實現
[main]
userRealm=com.itmyhome.UserRealm
securityManager.realms=$userRealm
接下來再調用subject.login(token)方法時會執行UserRealm類的doGetAuthenticationInfo()方法