本文内容大部分来自黑马视频的SpringBoot与Shiro整合-权限管理实战视频,在此记录为个人学习笔记。
可按步骤操作,无法实操的实战blog都是耍流氓。
文章目录
七、Shiro授权-使用Shiro过滤器实现授权页面拦截
1. 在ShiroConfig中添加过滤器
//授权过滤器:授权拦截后,shiro会自动跳转到未授权页面
filterMap.put("/add", "perms[user:add]");
filterMap.put("/*", "authc");
Tips:注意要写在/*之前,否则不会拦截
2. 添加设置未授权页面
(1)ShiroConfig中
//修改自动跳转的未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");
(2)UserController中
@RequestMapping("/unAuth")
public String unAuth() {
return "unAuth";
}
(3)添加unAuth.html
3. 测试
登录认证之后,访问/add页面会提示未授权,而/update可以正常访问。
八、Shiro授权-编写资源授权逻辑
刚才打印的log日志中可以看到,只要访问了需要授权访问的资源,就会执行UserRealm中的doGetAuthenticationInfo()方法,在该方法中给资源进行授权。
/**
* 执行授权逻辑
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("执行授权逻辑");
//给资源进行授权
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//添加资源的授权字符串
info.addStringPermission("user:add");
return info;
}
测试查看效果:日志中可以看到执行了该授权逻辑,现在可以访问/add了
九、Shiro授权-关联数据库动态授权
1. 修改数据表
给user表添加perms字段,插入两个测试用户
2. 一系列小修改
(1)User.java:添加perms属性和getter/setter
(2)UserMapper.java:
public User findById(Integer id);
(3)UserMapper.xml
<select id="findById" parameterType="int" resultType="User" >
select id,username,password,perms from user where id = #{value}
</select>
(4)UserService.java
public User findById(Integer id);
(5)UserServiceImpl.java
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
(6)给/update添加资源拦截
filterMap.put("/update", "perms[user:update]");
3. 修改UserRealm中的doGetAuthorizationInfo方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("执行授权逻辑");
//给资源进行授权
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
/*//添加资源的授权字符串
info.addStringPermission("user:add");*/
//获取当前用户
Subject subject=SecurityUtils.getSubject();
User user=(User)subject.getPrincipal();
//到数据库查询当前登录用户的授权字符串
User dbUser=userService.findById(user.getId());//通过当前登录用户id查找的数据库用户
info.addStringPermission(dbUser.getPerms());
return info;
}
将doGetAuthenticationInfo()方法的返回修改为
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
因为User user=(User)subject.getPrincipal();
所取得的当前登录用户就是从这里来的
4. 登录不同权限用户进行测试
各自有了各自的权限。
十、ThymeLeaf和shiro标签整合使用
1. 导入thymeleaf对shiro的扩展坐标
<!-- 导入thymeleaf对shiro的扩展坐标 -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
2. 配置ShiroDialect
ShiroConfig中
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
3. 在页面上使用shiro标签
<div shiro:hasPermission="user:add">
进入用户新增页面:<a href="add">用户新增</a>
</div>
<div shiro:hasPermission="user:update">
进入用户更新页面:<a href="update">用户更新</a>
</div>
4. 运行测试
不同权限用户登录,只显示了他有权限看到的内容。