通过shiro教程1,我们了解到仅仅在ini文件中定义数据源信息与实际开发环境存在较大的不兼容性,因此我们希望能够自定义realm。
实现自定义Realm的步骤如下:
创建自定义Realm的Java类:新建一个Java文件,继承AuthorizingRealm类,并重写两个抽象方法。
/** * 自定义的Realm * @author dengp */public class MyRealm extends AuthorizingRealm {/** * 认证方法 * @param token 就是我们在测试代码中定义的UsernamePasswordToken对象 * 有我们保存的需要验证的账号密码信息 */@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 获取账号信息 String principal = (String) token.getPrincipal(); // 正常逻辑此处应该根据账号去数据库中查询,此处我们默认账号为 root 密码123456 // 验证账号 if(!"root".equals(principal)){ // 账号错误 return null; } String pwd = "123456"; // 验证密码 AuthenticationInfo info = new SimpleAuthenticationInfo(principal, pwd, "myrealm"); return info;}/** * 授权方法 */@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // TODO Auto-generated method stub return null;}
}

配置ini.xml文件:
[main]自定义 realm
customRealm=com.dpb.realm.MyRealm
将realm设置到securityManager
securityManager.realms=$customRealm
测试:测试代码与上个案例完全相同。
@Testpublic void test() {// 1.获取SecurityManager工厂对象Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");// 2.通过Factory对象获取SecurityManager对象SecurityManager securityManager = factory.getInstance();// 3.将SecurityManager对象添加到当前运行环境中SecurityUtils.setSecurityManager(securityManager);// 4.获取Subject对象Subject subject = SecurityUtils.getSubject();AuthenticationToken token = new UsernamePasswordToken("root1", "12345");// 登录操作try { subject.login(token);} catch (UnknownAccountException e) { System.out.println("账号出错...");} catch(IncorrectCredentialsException e){ System.out.println("密码出错...");}// 获取登录的状态System.out.println(subject.isAuthenticated());
}



原理分析:
为什么要继承AuthorizingRealm?
在上个教程中,我们完整地分析了认证的流程,发现认证过程的核心代码是:
通义视频
通义万相AI视频生成工具
70 查看详情

核心方法是doGetAuthenticationInfo(token),在Realm的结构中:

AuthorizingRealm和AuthenticatingRealm都提供了doGetAuthenticationInfo(token)的抽象方法。但是AuthenticatingRealm中需要重写的抽象方法太多,而AuthorizingRealm只需要重写两个方法,且这两个方法都是我们需要使用的。因此选择继承AuthorizingRealm。
自定义的Realm什么时候被调用?

密码验证什么时候执行?
注意:自定义Realm中只完成了账号的认证。密码认证还是在AuthenticatingRealm中完成的,只是我们在自定义Realm中完成了密码的设置。



以上就是shiro教程2(自定义Realm)的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/466697.html
微信扫一扫
支付宝扫一扫