Shiro-全面详解(学习总结---从入门到深化)(下)

简介: 授权即认证通过后,系统给用户赋予一定的权限,用户只能根据权 限访问系统中的某些资源。所以在数据库中,用户需要和权限关 联。除了用户表和权限表,还需要创建角色表

 Shiro授权_权限表设计

2345_image_file_copy_143.jpg

授权即认证通过后,系统给用户赋予一定的权限,用户只能根据权 限访问系统中的某些资源。所以在数据库中,用户需要和权限关 联。除了用户表和权限表,还需要创建角色表,他们之间的关系如下:

2345_image_file_copy_144.jpg

用户角色,角色权限都是多对多关系,即一个用户拥有多个角色, 一个角色拥有多个权限。如:张三拥有总经理和股东的角色,而总 经理拥有查询工资、查询报表的权限;股东拥有查寻股权的权限, 这样张三就拥有了查询工资、查询报表、查询股权的权限。

接下来我们创建除users外的其余表:

CREATE TABLE `role`  (
  `rid` int(11) NOT NULL AUTO_INCREMENT,
  `roleName` varchar(255) CHARACTER SET utf8
COLLATE utf8_general_ci NULL DEFAULT NULL,
  `roleDesc` varchar(255) CHARACTER SET utf8
COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`rid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4
CHARACTER SET = utf8 COLLATE =
utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `role` VALUES (1,'总经理','管理整个公司');
INSERT INTO `role` VALUES (2,'股东','参与公司决策');
INSERT INTO `role` VALUES (3,'财务','管理公司资产');
CREATE TABLE `permission`  (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
`permissionName` varchar(255) CHARACTER
SET utf8 COLLATE utf8_general_ci NULL
DEFAULT NULL,
  `url` varchar(255) CHARACTER SET utf8
COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`pid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4
CHARACTER SET = utf8 COLLATE =
utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `permission` VALUES (1,'查询报表', '/reportform/find');
INSERT INTO `permission` VALUES (2,'查询工资', '/salary/find');
INSERT INTO `permission` VALUES (3,'查询税务', '/tax/find');
CREATE TABLE `users_role`  (
  `uid` int(255) NOT NULL,
  `rid` int(11) NOT NULL,
  PRIMARY KEY (`uid`, `rid`) USING BTREE,
  INDEX `rid`(`rid`) USING BTREE,
  CONSTRAINT `users_role_ibfk_1` FOREIGN KEY
(`uid`) REFERENCES `users` (`uid`) ON DELETE
RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `users_role_ibfk_2` FOREIGN KEY
(`rid`) REFERENCES `role` (`rid`) ON DELETE
RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8
COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `users_role` VALUES (1, 2);
INSERT INTO `users_role` VALUES (1, 3);
CREATE TABLE `role_permission`  (
  `rid` int(11) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`rid`, `pid`) USING BTREE,
  INDEX `pid`(`pid`) USING BTREE,
  CONSTRAINT `role_permission_ibfk_1`
FOREIGN KEY (`rid`) REFERENCES `role`
(`rid`) ON DELETE RESTRICT ON UPDATE
RESTRICT,
  CONSTRAINT `role_permission_ibfk_2`
FOREIGN KEY (`pid`) REFERENCES `permission`
(`pid`) ON DELETE RESTRICT ON UPDATE
RESTRICT ) ENGINE = InnoDB CHARACTER SET = utf8
COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `role_permission` VALUES (1, 1);
INSERT INTO `role_permission` VALUES (2, 1);
INSERT INTO `role_permission` VALUES (1, 2);
INSERT INTO `role_permission` VALUES (3, 2);
INSERT INTO `role_permission` VALUES (1, 3);
INSERT INTO `role_permission` VALUES (2, 3);

Shiro授权_数据库查询权限

2345_image_file_copy_145.jpg

在认证后进行授权需要根据用户id查询到用户的权限,写法如下:

1、编写用户、角色、权限实体类

@Data
public class Users implements Serializable
{
    private Integer uid;
    private String username;
    private String password;
    private String salt;
}
// 角色
@Data
public class Role implements Serializable{
    private Integer rid;
    private String roleName;
    private String roleDesc;
}
// 权限
@Data
public class Permission implements Serializable{
    private Integer pid;
    private String permissionName;
    private String url;
}

2、修改UsersMapper接口

// 根据用户id查询权限
List<Permission> findPermissionById(Integer id);

3、在resources目录中编写UsersMapper的映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itbaizhan.myshiro1.mapper.UsersMapper">
    <select id="findPermissionById" resultType="com.itbaizhan.myshiro1.domain.Permission">
       SELECT DISTINCT permission.pid,permission.permissionName,permission.url FROM
           users
               LEFT JOIN users_role on users.uid = users_role.uid
               LEFT JOIN role on users_role.rid = role.rid
               LEFT JOIN role_permission on role.rid = role_permission.rid
               LEFT JOIN permission on role_permission.pid = permission.pid
       where users.uid = #{uid}
    </select>
</mapper>

4、测试方法

@SpringBootTest
public class UserMapperTest {
    @Autowired
    private UsersMapper usersMapper;
    @Test
    public void testFindPermissionById(){
        List<Permission> permissions = usersMapper.findPermissionById(1);
        permissions.forEach(System.out::println);
   }
}

Shiro授权_在Realm进行授权

2345_image_file_copy_146.jpg

在自定义Realm中可以自定义授权方法:

// 自定义授权方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //1.拿到用户认证信息
    Users users = (Users) principalCollection.getPrimaryPrincipal();
    //2.从数据库中查询权限
    List<Permission> permissions = usersMapper.findPermissionById(users.getUid());
    //3.遍历权限对象,将所有权限名交给Shiro管理
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    for (Permission permission : permissions) {
         authorizationInfo.addStringPermission(permission.getUrl());
   }
    return authorizationInfo;
}

Shiro授权_过滤器配置鉴权

2345_image_file_copy_147.jpg

Shiro可以根据用户拥有的权限,控制具体资源的访问,这一过程称 为鉴权。在Shiro中,可以通过过滤器进行鉴权配置:

2345_image_file_copy_148.jpg

// 配置过滤器
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
    // 1.创建过滤器工厂
    ShiroFilterFactoryBean filterFactory=new ShiroFilterFactoryBean();
    // 2.过滤器工厂设置SecurityManager
   filterFactory.setSecurityManager(securityManager);
    // 3.设置shiro的拦截规则
    Map<String,String> filterMap=new HashMap<>();
    // 不拦截的资源
    filterMap.put("/login.html","anon");
    filterMap.put("/fail.html","anon");
    filterMap.put("/user/login","anon");
    filterMap.put("/css/**","anon");
    // 鉴权过滤器,要写在/**之前,否则认证都无法通过
    filterMap.put("/reportform/find","perms[/reportform/find]");
    filterMap.put("/salary/find","perms[/salary/find]");
    filterMap.put("/staff/find","perms[/staff/find]");
    // 其余资源都需要认证,authc过滤器表示需要认证才能进行访问; 
    //user过滤器表示配置记住我或认证都可以访问
    //filterMap.put("/**","authc");
    filterMap.put("/user/pay","authc");
    filterMap.put("/**", "user");
    // 4.将拦截规则设置给过滤器工厂
    filterFactory.setFilterChainDefinitionMap(filterMap);
    // 5.登录页面
    filterFactory.setLoginUrl("/login.html");
    return filterFactory;
}
// 编写测试控制器
@RestController
public class MyController {
    @GetMapping("/reportform/find")
    public String findReportform(){
        return "查询报表";
   }
    @GetMapping("/salary/find")
    public String findSalary(){
        return "查询工资";
   }
    @GetMapping("/staff/find")
    public String findStaff(){
        return "查询员工";
   }
}

此时如果权限不足会抛出401异常,我们可以自定义权限不足的跳转页面:

1、编写权限不足页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>权限不足</title>
</head>
<body>
    <h1>您的权限不足,请联系管理员!</h1>
</body>
</html>

2、配置权限不足的跳转页面

// 配置过滤器
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
    // 1.创建过滤器工厂
    ShiroFilterFactoryBean filterFactory=new ShiroFilterFactoryBean();
    // 2.过滤器工厂设置SecurityManager
    filterFactory.setSecurityManager(securityManager);
    // 3.设置shiro的拦截规则
    Map<String,String> filterMap=new HashMap<>();
    // 不拦截的资源
    filterMap.put("/login.html","anon");
    filterMap.put("/fail.html","anon");
    filterMap.put("/noPermission.html","anon");
    filterMap.put("/user/login","anon");
    filterMap.put("/css/**","anon");
    // 鉴权过滤器
    filterMap.put("/reportform/find","perms[/reportform/find]");
    filterMap.put("/salary/find","perms[/salary/find]");
    filterMap.put("/staff/find","perms[/staff/find]");
    // 其余资源都需要认证,authc过滤器表示需要认证才能进行访问; 
    //user过滤器表示配置记住我或认证都可以访问
    //filterMap.put("/**","authc");
    filterMap.put("/user/pay","authc");
    filterMap.put("/**", "user");
    //4.将拦截规则设置给过滤器工厂
    filterFactory.setFilterChainDefinitionMap(filterMap);
    // 5.登录页面
    filterFactory.setLoginUrl("/login.html");
    // 6.权限不足访问的页面
    filterFactory.setUnauthorizedUrl("/noPermission.html");
    return filterFactory;
}

Shiro授权_注解配置鉴权

2345_image_file_copy_149.jpg

除了过滤器,Shiro也提供了一些鉴权的注解。我们可以使用注解配置鉴权。

@RequiresGuest:不认证即可访问的资源。

@RequiresUser:通过登录方式或“记住我”方式认证后可以访问资源。

@RequiresAuthentication:通过登录方式认证后可以访问资 源。

@RequiresRoles:认证用户拥有特定角色才能访问的资源

@RequiresPermissions:认证用户拥有特定权限才能访问的资源

1、在配置类开启Shiro注解

// 开启shiro注解的支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
    advisor.setSecurityManager(securityManager);
    return advisor;
}
// 开启aop注解支持
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
    defaultAAP.setProxyTargetClass(true);
    return defaultAAP;
}

2、在控制器方法上添加鉴权注解

@GetMapping("/test/index")
@RequiresGuest
public String testIndex() {
    return "访问首页";
}
@GetMapping("/test/user")
@RequiresUser
public String testUser() {
    return "用户中心";
}
@GetMapping("/test/pay")
@RequiresAuthentication
public String testPay() {
    return "支付中心";
}
@GetMapping("/tax/find")
@RequiresPermissions("/tax/find")
public String taxFind() {
    return "查询税务";
}
@GetMapping("/address/find")
@RequiresPermissions("/address/find")
public String addressFind() {
    return "查询地址";
}

2345_image_file_copy_150.jpg

Shiro授权_Thymeleaf中进行鉴权

2345_image_file_copy_151.jpg Shrio可以在一些视图技术中进行控制显示效果。例如Thymeleaf 中,只有认证用户拥有某些权限才会展示一些菜单。

1、在pom中引入Shiro和Thymeleaf的整合依赖

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extrasshiro</artifactId>
    <version>2.0.0</version>
</dependency>

2、在配置文件中注册ShiroDialect

@Bean
public ShiroDialect shiroDialect(){
    return new ShiroDialect();
}

3、在Thymeleaf中使用Shiro标签,控制前端的显示内容

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>主页面</title>
</head>
<body>
<h1>主页面</h1>
<ul>
    <li shiro:hasPermission="/reportform/find">
      <a href="/reportform/find">查询报表</a></li>
   <li shiro:hasPermission="/salary/find">
     <a href="/salary/find">查询工资</a></li>
   <li shiro:hasPermission="/staff/find">
     <a href="/staff/find">查询员工</a></li>
</ul>
    <h2><a href="/user/logout">退出登录</a></h2>
</body>
</html>

Shiro授权_缓存

2345_image_file_copy_152.jpg

在Shiro中,每次拦截请求进行鉴权,都会去数据库查询该用户的权 限信息。因为用户的权限信息在短时间内是不可变的,每次查询出 来的数据其实都是重复数据,此时就会非常浪费资源。所以一般我 们会将权限数据放在缓存中进行管理,这样我们就不用每次请求都 查询数据库,提升了系统性能。

缓存

缓存即存在于内存中的一块数据。数据库的数据是存储在硬盘上 的,而内存的读写效率要远远的高于数据库。但硬盘中保存的数据 是持久化数据,断电后依然存在;而内存中保存的是临时数据,随 时可能清空。所以我们为了提升系统性能,减少程序和数据库的交 互,会将经常查询但不常改变的,改变后对结果影响不大的数据放 入缓存中。

Shiro支持多种缓存产品,在课程中我们使用ehcache缓存用户的权限数据。

ehcache

ehcache是用来管理缓存的一个工具,其缓存的数据可以放在内存 中,也可以放在硬盘上。ehcache的核心是CacheManager,一切 的ehcache的应用都是从CacheManager开始的。

1、引入shiro和ehcache整合包

<!-- shiro和ehcache整合包 -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.9.0</version>
</dependency>

2、创建配置文件shiro-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
        默认缓存设置
        maxElementsInMemory:缓存最大数目
        maxEntriesLocalHeap:指定允许在内存中存放元素的最大数量。
        timeToIdleSeconds:一个元素在不被请求的情况下允许在缓存中存活的最大时间。0表示永久有效。
        timeToLiveSeconds:无论一个元素闲置与否,其允许在Cache中存活的最大时间。0表示永久有效。
        diskExpiryThreadIntervalSeconds:检查元素是否过期的线程多久运行一次
      -->
    <defaultCache
            maxElementsInMemory="10000"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"/>
    <!-- 授权缓存设置 -->
    <cache name="authorizationCache"
           maxEntriesLocalHeap="2000"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0">
    </cache>
</ehcache>

3、在配置文件创建CacheManager

// 创建CacheManager
@Bean
public EhCacheManager ehCacheManager() {
    EhCacheManager ehCacheManager = new EhCacheManager();
    ehCacheManager.setCacheManagerConfigFile( "classpath:shiro-ehcache.xml");
    return ehCacheManager;
}

4、在SecurityManager中配置CacheManager

@Bean
public DefaultWebSecurityManager securityManager(MyRealm myRealm,MyRealm2 myRealm2,
       SessionManager sessionManager, CookieRememberMeManager rememberMeManager,
       EhCacheManager ehCacheManager){
      DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    // 自定义Realm放入SecurityManager中
    // securityManager.setRealm(myRealm);
    // 设置Realm管理者(需要设置在Realm之前)
    securityManager.setAuthenticator(modularRealmAuthenticator());
    List<Realm> realms = new ArrayList();
    realms.add(myRealm);
    //realms.add(myRealm2);
    securityManager.setRealms(realms);
    securityManager.setSessionManager(sessionManager);
    securityManager.setRememberMeManager(rememberMeManager);
    securityManager.setCacheManager(ehCacheManager);
    return securityManager;
}

5、启动项目,测试权限缓存。

目录
相关文章
|
2天前
|
JSON 前端开发 Java
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
46 0
|
10月前
|
存储 缓存 安全
Java安全框架(课时二十三)笔记内容十三
Java安全框架(课时二十三)笔记内容十三
157 0
|
存储 缓存 安全
Shiro-全面详解(学习总结---从入门到深化)(上)
Shiro是apache旗下的一个开源安全框架,它可以帮助我们完成身 份认证,授权、加密、会话管理等功能。
194 0
Shiro-全面详解(学习总结---从入门到深化)(上)
|
算法 安全 Java
Shiro-全面详解(学习总结---从入门到深化)(中)
如果有多个Realm,怎样才能认证成功,这就是认证策略。认证策 略主要使用的是 AuthenticationStrategy 接口
125 0
Shiro-全面详解(学习总结---从入门到深化)(中)
|
JSON 前端开发 JavaScript
|
前端开发 安全 Java
SpringMVC-全面详解(学习总结---从入门到深化)(下)
将文件上传到服务器后,有时我们需要让用户下载上传的文件,接下来我们编写文件下载功能
82 0
SpringMVC-全面详解(学习总结---从入门到深化)(下)
|
存储 前端开发 Java
SpringMVC-全面详解(学习总结---从入门到深化)(上)
MVC全称Model View Controller,是一种设计创建Web应用程序的 模式。
129 0
SpringMVC-全面详解(学习总结---从入门到深化)(上)
|
XML Java 数据库连接
Spring-全面详解(学习总结---从入门到深化)(中)
注解配置和xml配置对于Spring的IOC要实现的功能都是一样的,只是配置的形式不一样。
209 1
Spring-全面详解(学习总结---从入门到深化)(中)
|
XML Java 数据库连接
|
XML Java 应用服务中间件
Spring-全面详解(学习总结---从入门到深化)(上)
Spring是一个开源框架,为简化企业级开发而生。它以IOC(控制 反转)和AOP(面向切面)为思想内核,提供了控制层 SpringMVC、数据层SpringData、服务层事务管理等众多技术,并 可以整合众多第三方框架。
283 0
Spring-全面详解(学习总结---从入门到深化)(上)