博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
权限框架 - shiro 自定义realm
阅读量:7065 次
发布时间:2019-06-28

本文共 2187 字,大约阅读时间需要 7 分钟。

上篇文章中是使用的默认realm来实现的简单登录,这仅仅只是个demo,真正项目中使用肯定是需要连接数据库的

首先创建自定义realm文件,如下:

在shiro中注入自定义realm的完全限定类名:

1 [main]2 # your custom realm path3 fooRealm=com.lee.shiro.realm.FooRealm4 # DI such as spring DI5 securityManager.realms=$fooRealm

自定义realm认证:

1     /** 2      *  设置realm的名称 3      */ 4     @Override 5     public void setName(String name) { 6         super.setName("fooRealm"); 7     } 8  9     /**10      * 认证11      */12     @Override13     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {14 15         // token是用户输入的相关信息16         // 从token中取出身份信息, 即用户的username17         String username = (String)token.getPrincipal();18 19         // 根据用户名username从数据库查询密码password20         // 如果查询不到返回null21         // String password = userService.queryPwdByUserName(username)22         23         // 假设数据库查询出来的密码为如下24         String password = "1234567";25 26         // 如果查询到返回认证信息AuthenticationInfo27         SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());28 29         return simpleAuthenticationInfo;30     }

执行认证:

/**     *      * @Description: 自定义realm     *      * @author leechenxiang     * @date 2016年6月11日 下午9:07:27     */    @Test    public void testFooRealm() {        // 创建SecurityManager工厂,通过ini配置文件创建 SecurityManager工厂        Factory
factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini"); // 创建SecurityManager SecurityManager securityManager = factory.getInstance(); // 设置SecurityManager到运行环境中,保持单例模式 SecurityUtils.setSecurityManager(securityManager); // 从SecurityUtils里边创建一个subject Subject subject = SecurityUtils.getSubject(); // 在认证提交前准备token(令牌) // 这里的账号和密码 将来是由用户输入进去 UsernamePasswordToken token = new UsernamePasswordToken("lee", "123456"); try { // 执行认证提交 subject.login(token); } catch (AuthenticationException e) { e.printStackTrace(); } // 是否认证通过 boolean isAuthenticated = subject.isAuthenticated(); System.out.println("是否认证通过:" + isAuthenticated); }

done...

 

转载地址:http://iqill.baihongyu.com/

你可能感兴趣的文章
CAShapeLayer(持续更新)
查看>>
JAVA UUID 生成唯一标识
查看>>
spring学习笔记(4)依赖注入详解
查看>>
菜鸟学自动化测试(五)-----selenium命令之定位页面元素
查看>>
【SICP练习】64 练习2.35
查看>>
PSK星座对象(constellation.cc)
查看>>
Linux链接脚本学习--lds
查看>>
Android将list数据通过LitePal保存到本地(集合保存到本地)
查看>>
hdu 1285 确定比赛名次
查看>>
Eureka微服务实战-服务提供者
查看>>
简单的原生ajax
查看>>
h5开发坑点小总结
查看>>
几分钟内提升技能的8个 JavaScript 方法!
查看>>
mac显示隐藏文件
查看>>
Android 插件化原理-好文收集(陆续中。。。)
查看>>
双亲委派模型与Tomcat类加载架构
查看>>
Highcharts tooltip显示数量和百分比
查看>>
小程序兼容iphoneX(齐刘海)代码,mpvue的写法
查看>>
小米设备怎么不ROOT激活Xposed框架的步骤
查看>>
Vue Router
查看>>