Apache Shiro 使用手册(四)Realm 实现
在认证、授权内部实现机制中都有提到,最终处理都将交给real进行处理。因为在shiro中,最终是通过realm来获取应用程序中的用户、角色及权限信息的。通常情况下,在realm中会直接从我们的数据源中获取shiro需要的验证信息。可以说,realm是专用于安全框架的dao.
一、认证实现
正如前文所提到的,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;
}
}以上就是Apache Shiro 使用手册(四)Realm 实现的内容,更多相关内容请关注PHP中文网(www.php.cn)!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号