springboot 集成 shiro

如果没有了解shiro 可以先去学习shiro:https://www.cnblogs.com/wujiaofen/p/11088973.html

springboot 整合shiro:

1、 在spring boot 项目中导入jar

2、    <!-- shiro -->
3、            <dependency>
4、                <groupId>org.apache.shiro</groupId>
5、                <artifactId>shiro-spring</artifactId>
6、                <version>1.4.0</version>
7、            </dependency>
8、            <!-- shiro-ehcache -->
9、            <dependency>
10、                <groupId>org.springframework.boot</groupId>
11、                <artifactId>spring-boot-starter-cache</artifactId>
12、            </dependency>
13、            <dependency>
14、                <groupId>net.sf.ehcache</groupId>
15、                <artifactId>ehcache</artifactId>
16、            </dependency>
17、            <dependency>
18、                <groupId>org.apache.shiro</groupId>
19、                <artifactId>shiro-ehcache</artifactId>
20、                <version>1.4.0</version>
21、            </dependency>
22、            <dependency>
23、                <groupId>net.sf.json-lib</groupId>
24、                <artifactId>json-lib</artifactId>
25、                <version>2.2.3</version>
26、                <classifier>jdk15</classifier>
27、        </dependency>

2、创建基本配置类shiroConfig 和缓存类

/**
 * shiro 配置类
 * @author Administrator
 *
 */
@Configuration
public class ShiroConfig {

    /**
     * shiro 过滤器配置
     * @param securityManager
     * @return
     */
    
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager)
    {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);    
        /**
         * 过滤器链,对URL配置过滤规则 
         * authc:所有url都必须认证通过才可以访问
         * anon:所有url都都可以匿名访问
         * user:表示身份认证通过或通过记住我认证通过的可以访问
         * 注意点:过滤链定义,从上向下顺序执行,一般将/**放在最为下边 
         * 
         */
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //initPermission
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/initPermission", "anon");
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/logout", "logout"); //配置退出
        filterChainDefinitionMap.put("/**", "user");
        //如果没有认证将要跳转的登陆地址,http可访问的url,如果不在表单认证过虑器FormAuthenticationFilter中指定此地址就为身份认证地址
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        
        
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
    
    /**
     * 加密方式
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher()
    {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //散列次数
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }
    
    /**
     * 认证配置
     * @return
     */
    @Bean
    public MyRealm getRealm()
    {
        MyRealm  myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        myRealm.setCacheManager(ehCacheManager());
        return myRealm;
    }
    
    /**
     * 安全管理器配置
     * @return
     */
    @Bean
    public SecurityManager getSecurityManager()
    {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(getRealm());
        securityManager.setCacheManager(ehCacheManager());
        //注入记住我管理器
        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }
    
    /**
     * 缓存管理器
     * @return
     */
    @Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml");
        return cacheManager;
    }
    
    /**
      * cookie对象;
      * rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cookie的有效时间等等。
      * @return
     */
    @Bean
    public SimpleCookie rememberMeCookie(){
          //System.out.println("ShiroConfiguration.rememberMeCookie()");
          //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
          SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
          //<!-- 记住我cookie生效时间30天 ,单位秒;-->
          simpleCookie.setMaxAge(259200);
          return simpleCookie;
    }
    
    /**
      * cookie管理对象;
      * rememberMeManager()方法是生成rememberMe管理器,而且要将这个rememberMe管理器设置到securityManager中
      * @return
     */
    @Bean
    public CookieRememberMeManager rememberMeManager(){
          //System.out.println("ShiroConfiguration.rememberMeManager()");
          CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
          cookieRememberMeManager.setCookie(rememberMeCookie());
          //rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
          cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
          return cookieRememberMeManager;
    }

    /**
     * 开启@RequirePermission注解的配置
     * 要结合DefaultAdvisorAutoProxyCreator一起使用,或者导入aop的依赖
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager)
    {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    
    /**
     * aop代理
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
          DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
          advisorAutoProxyCreator.setProxyTargetClass(true);
          return advisorAutoProxyCreator;
    }
    /**
     * 定义Spring MVC的异常处理器
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理
        mappings.setProperty("UnauthorizedException","403");//处理shiro的认证未通过异常
        r.setExceptionMappings(mappings);  // None by default
        r.setDefaultErrorView("error");    // No default
        r.setExceptionAttribute("ex");     // Default is "exception"
        return r;
    }
}

缓存配置类:

@Configuration
public class EhcacheConfig {

    /**
     * 设置为共享模式
     * @return
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }
}

同时需要在resources 源目录添加shiro-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
    <diskStore path="java.io.tmpdir"/>
    <cache name="users"
           timeToLiveSeconds="300"
           maxEntriesLocalHeap="1000"/>
    <!--
        name:缓存名称。
        maxElementsInMemory:缓存最大个数。
        eternal:对象是否永久有效,一但设置了,timeout将不起作用。
        timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
        timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
        overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
        diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
        maxElementsOnDisk:硬盘最大缓存个数。
        diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
        diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
        memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
        clearOnFlush:内存数量最大时是否清除。
    -->
    <defaultCache name="defaultCache"
                  maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  overflowToDisk="false"
                  maxElementsOnDisk="100000"
                  diskPersistent="false"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU"/>
</ehcache>

3、自定义Realm 继承AuthorizingRealm 实现doGetAuthenticationInfo【认证】doGetAuthorizationInfo【授权】即可

原文地址:https://www.cnblogs.com/wujiaofen/p/11095140.html