Shiro的学习(三)

1、授权

1.1、过滤器授权

需求:假设在首页有一个按钮 这个按钮访问后台数据的addUser接口,这个接口必须要用户具有 user:add权限才能访问
在realm中查询用户的权限和角色放到simpleAuthorizationInfo中

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      	//获取用户信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        //模拟数据库查询权限
        Set<String> perms = new HashSet<>();
        perms.add("user:add");
        perms.add("user:delete");
        //模拟数据库查询角色
        Set<String> roles = new HashSet<>();
        roles.add("buyer");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
        simpleAuthorizationInfo.setStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

在配置文件中配置过滤器授权

map.put("/addUser","perms[user:add]");  //访问addUser时必须要有user:add权限

这样在访问地址为addUser的时候,有权限才能访问

1.2、注解授权

首先在配置文件中配置aop对注解的支持

@Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            @Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

在方法上使用注解来完成权限的判断

   @RequestMapping("toDelete")
    @RequiresPermissions({"user:delete"})   //判断是否有该权限
//    @RequiresRoles("")  判断是否有该角色
    public String toDelete(){
        return "delete";
    }

1.3、标签授权

在这里我使用的是thymeleaf
1.导包

<!--导入thymeleaf对shiro的支持包-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

2.配置方言

 /*配置shiro-dialect这个方言*/
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

3.使用shiro的标签
shiro:authenticated 认证
shiro:notAuthenticated 没有认证
shiro:guest 相当于游客登录
<shiro:hasAnyRoles name=“abc,123” > 在有abc或者123角色时
<shiro:hasRole name=“abc”> 拥有角色abc
<shiro:lacksRole name=“abc”> 没有角色abc
<shiro:hasPermission name=“abc”> 拥有权限资源abc
<shiro:lacksPermission name=“abc”> 没有abc权限
shiro:principal 显示用户信息

2、缓存的使用

在没有使用缓存时,每一次请求都要调用doGetAuthenticationInfo方法来授权,但是用户的权限一般而言并不会频繁的更改,为了减少服务器的压力,我们可以在登录成功授权完成之后将用户信息存储在缓存中,这样我们要使用时就不再需要访问数据库了,直接从缓存中获取

1.导包

 <!--缓存-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.4.0</version>
        </dependency>

2.在resources下创建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:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home – 用户主目录
       user.dir  – 用户当前工作目录
       java.io.tmpdir – 默认临时文件路径
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>
 
    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
 

3.在shiro.config配置类中进行缓存的配置

	@Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
        return ehCacheManager;
    }

4.在securityManager中上进行设置

//设置缓存
securityManager.setCacheManager(ehCacheManager());

这样请求时信息会默认存在缓存中,而不会每次都去数据库中查询

3、session的管理

1.在ShiroConfig中进行配置

//Session的管理
    public DefaultWebSessionManager sessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        //Session到期的时候是否自动删除
        sessionManager.setDeleteInvalidSessions(true);
        //设置session的超时时间
        sessionManager.setGlobalSessionTimeout(1);
        return sessionManager;
    }

2.在securityManager中设置session

 //设置Session的管理
securityManager.setSessionManager(sessionManager());

这样就完成了session的简单配置了

4、rememberMe

Shiro 提供了记住我(RememberMe)的功能,比如访问一些网站时,关闭了浏览器,下次再打开时还是能记住你是谁,下次访问时无需再登录即可访问,基本流程如下:
1、首先在登录页面选中 RememberMe 然后登录成功;如果是浏览器登录,一般会把 RememberMe 的Cookie 写到客户端并保存下来;
2、关闭浏览器再重新打开;会发现浏览器还是记住你的;
3、访问一般的网页服务器端还是知道你是谁,且能正常访问;

配置shiro.config
/**
     * rememberMe功能的实现
     * @return
     */
    public CookieRememberMeManager cookieRememberMeManager(){
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(simpleCookie());
        return cookieRememberMeManager;
    }

    /**
     * 自定义cookie对象
     * @return
     */
    public SimpleCookie simpleCookie(){
        SimpleCookie simpleCookie = new SimpleCookie();
        simpleCookie.setName("rememberMe");
        //记住的最大值,单位时间是秒
        simpleCookie.setMaxAge(259200);
        return simpleCookie;
    }
编写前端页面
<form action="/login" method="post">
    用户名: <input type="text" name="username"><span th:text="${usernameError}"></span><br>
    密码: <input type="password" name="password"><span th:text="${passwordError}"></span>
    <span th:text="${otherError}"></span><br>
    记住我: <input type="checkbox" name="rememberMe">
    <input type="submit" value="登录">
</form>
在认证的token上设置记住我的这个方法

此时的remember从前端传递过来的

 //封装成请求对象
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        //设置记住我的这个功能
        token.setRememberMe(rememberMe);
在过滤器配置中配置哪些页面使用了rememberMe这个功能之后可以直接访问
maps.put("/addUser","user"); //这个设置的意思:假设我们使用了rememberMe这个功能那么 请求/addUser地址 就可以直接访问不需要认证了
maps.put("/toIndex","user"); //这个设置的意思:假设我们使用了rememberMe这个功能那么 请求/toIndex地址 就可以直接访问不需要认证了
maps.put("/toDeleteUser","user");
发布了11 篇原创文章 · 获赞 6 · 访问量 192

猜你喜欢

转载自blog.csdn.net/X_Q_B_J/article/details/104546302