`

SpringBoot2.0集成Shiro并使用EhCache缓存

阅读更多

使用EhCache同时缓存数据库数据及其它需要缓存的数据和shrio共享(shiro主要用于会话的存储和持久化),集成整合步骤如下:

一:集成EhCache

<1>、在pom.xml文件中添加以下依赖。

        <!-- 开启 cache 缓存 -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-cache</artifactId>

        </dependency>

        <!-- ehcache 缓存 -->

        <dependency>

            <groupId>net.sf.ehcache</groupId>

            <artifactId>ehcache</artifactId>

        </dependency>

 <2>、添加配置文件 ehcache.xml,放在resources下,内容如下。

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"

        updateCheck="false">

    <defaultCache

            eternal="false"

            maxElementsInMemory="1000"

            overflowToDisk="false"

            diskPersistent="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="600"

            memoryStoreEvictionPolicy="LRU" />

    <cache

            name="permissionCache"

            eternal="false"

            maxElementsInMemory="100"

            overflowToDisk="false"

            diskPersistent="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="300"

            memoryStoreEvictionPolicy="LRU" />

</ehcache>

<3>、在启动类加上启用缓存注解@EnableCaching。

<4>、经过上述步骤后,就可以使用缓存注解@Cacheable,@CachePut等。

二:集成Shiro并使用EhCache缓存

<1> 、在pom.xml文件中添加以下依赖。

        <!-- shiro -->

        <dependency>

            <groupId>org.apache.shiro</groupId>

            <artifactId>shiro-spring</artifactId>

            <version>${shiro-spring.version}</version>

        </dependency>

        <!-- shiro ehcache -->

        <dependency>

            <groupId>org.apache.shiro</groupId>

            <artifactId>shiro-ehcache</artifactId>

            <version>${shiro-ehcache.version}</version>

        </dependency>

 <2>、编写Shiro的Realm验证,参考代码如下。

public class ShiroRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource

    private IUserService iUserService;

    @Resource

    private ILoginLogService iloginLogService;

    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        logger.info("权限配置----->ShiroRealm.doGetAuthorizationInfo()" );

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();

        authorizationInfo.addRole(userInfo.getRoleInfo().getRoleCode());

        for (Permission p : userInfo.getRoleInfo().getPermissions()) {

            authorizationInfo.addStringPermission(p.getPermissionCode());

        }

        //授权成功添加登录日志

        addLoginLog(userInfo);

        return authorizationInfo;

    }

    /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确*/

    @Override

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        logger.info("ShiroRealm.doGetAuthenticationInfo()" );

        //获取用户的输入的账号.

        String username = (String) token.getPrincipal();

        //通过username从数据库中查找 User对象,如果找到,没找到.

        //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法

        UserInfo userInfo = iUserService.findUserInfo(username);

        logger.info("----->userInfo=" + userInfo);

        if (userInfo == null) {

            throw new AccountException();

        } else if (userInfo.getState() == 0) {

            throw new DisabledAccountException();

        } else if (userInfo.getState() == 2) {

            throw new LockedAccountException();

        }

        //保存登录用户ID

        Session session = SecurityUtils.getSubject().getSession();

        session.setAttribute(Constant.LOGIN_USER_ID, userInfo.getId());

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(

                userInfo, //用户信息

                userInfo.getPassWord(), //密码

                ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt

                getName()  //realm name

        );

        return authenticationInfo;

    }

    private void addLoginLog(UserInfo userInfo) {

        LoginLog loginLog = new LoginLog();

        loginLog.setUserId(userInfo.getId());

        loginLog.setUserName(userInfo.getUserName());

        loginLog.setIpAddress(SecurityUtils.getSubject().getSession().getAttribute(Constant.LOGIN_IP_ADDRESS).toString());

        loginLog.setGeographyLocation(AddressUtils.getAddressByIp(loginLog.getIpAddress()));

        iloginLogService.insert(loginLog);

    }

}

 <3>、添加Shiro的配置类,参考代码如下。

@Configuration

public class ShiroConfig {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean

    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {

        logger.info("ShiroConfiguration.shirFilter()" );

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //获取filters

        Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();

        //将自定义的FormAuthenticationFilter注入shiroFilter中(验证码校验)

        filters.put("authc" , new CustomFormAuthenticationFilter());

        //拦截器.

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 配置不会被拦截的链接 顺序判断

        filterChainDefinitionMap.put("/static/**" , "anon" );

        filterChainDefinitionMap.put("/kaptcha/**" , "anon" );

        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了

        filterChainDefinitionMap.put("/logout" , "logout" );

        //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;

        //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->

        filterChainDefinitionMap.put("/**" , "authc" );

        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面

        shiroFilterFactoryBean.setLoginUrl("/login" );

        // 登录成功后要跳转的链接

        shiroFilterFactoryBean.setSuccessUrl("/index" );

        //未授权界面;

        shiroFilterFactoryBean.setUnauthorizedUrl("/error/403" );

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;

    }

    /**

    * 凭证匹配器

    * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了)

    *

    * @return

    */

    @Bean

    public HashedCredentialsMatcher hashedCredentialsMatcher() {

        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        hashedCredentialsMatcher.setHashAlgorithmName("md5" );//散列算法:这里使用MD5算法;

        hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));

        return hashedCredentialsMatcher;

    }

    /**

    * 自定义身份认证realm

    *

    * @return

    */

    @Bean

    public ShiroRealm shiroRealm() {

        ShiroRealm shiroRealm = new ShiroRealm();

        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());

        return shiroRealm;

    }

    @Bean

    public EhCacheManager ehCacheManager(CacheManager cacheManager) {

        EhCacheManager em = new EhCacheManager();

        //将ehcacheManager转换成shiro包装后的ehcacheManager对象

        em.setCacheManager(cacheManager);

        //em.setCacheManagerConfigFile("classpath:ehcache.xml");

        return em;

    }

    @Bean

    public SessionDAO sessionDAO(){

        return new MemorySessionDAO();

    }

    /**

    * shiro session管理

    */

    @Bean

    public DefaultWebSessionManager sessionManager() {

        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

        sessionManager.setSessionDAO(sessionDAO());

        return sessionManager;

    }

    @Bean

    public SecurityManager securityManager(EhCacheManager ehCacheManager) {

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置realm

        securityManager.setRealm(shiroRealm());

        // 自定义缓存实现

        securityManager.setCacheManager(ehCacheManager);

        // 自定义session管理

        securityManager.setSessionManager(sessionManager());

        return securityManager;

    }

    /**

    * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证

    * 配置以下两个bean(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)即可实现此功能

    *

    * @return

    */

    @Bean

    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {

        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();

        advisorAutoProxyCreator.setProxyTargetClass(true);

        return advisorAutoProxyCreator;

    }

    /**

    * 开启shiro aop注解支持.

    * 使用代理方式;所以需要开启代码支持;

    *

    * @param securityManager

    * @return

    */

    @Bean

    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {

        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();

        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);

        return authorizationAttributeSourceAdvisor;

    }

}

注意:

@Bean

public EhCacheManager ehCacheManager(CacheManager cacheManager) {

    EhCacheManager em = new EhCacheManager();

    //将ehcacheManager转换成shiro包装后的ehcacheManager对象

    em.setCacheManager(cacheManager);

    //em.setCacheManagerConfigFile("classpath:ehcache.xml");

    return em;

}

如上是配置Shiro的缓存管理器org.apache.shiro.cache.ehcach.EhCacheManager,上面方法的参数是把Spring容器中的cacheManager对象注入到EhCacheManager中,这样就实现了Shiro和缓存注解使用同一种缓存方式。

三:代码示例

Gitee:https://gitee.com/xieke90/common-admin/tree/SpringBoot2.X_EhCache

 

转载请注明出处:https://xieke90.iteye.com/blog/2440426

 

1
0
分享到:
评论

相关推荐

    springboot2.0整合Shiro

    SpringBoot 2.0 整合 Apache Shiro 是一个常见的安全框架集成,它为Web应用程序提供了用户认证和授权的功能。SpringBoot的优雅简洁与Shiro的强大安全特性相结合,可以简化开发过程,使得权限管理变得更加高效和便捷...

    springboot2.0+shiro+jwt后台权限管理系统。 权限控制的方式为 RBAC.zip

    springboot2.0+shiro+jwt+layui+thymeleaf+swagger+mybatis后台权限管理系统。 权限控制的方式为 RBAC。代码通熟易懂 、JWT(无状态token)过期自动刷新,数据全程 ajax 获取,封装 ajax 工具类、菜单无线层…-...

    采用SpringBoot2.0、MyBatis-Plus、Shiro框架,开发的一套权限系统.zip

    采用SpringBoot2.0、MyBatis-Plus、Shiro框架,开发的一套权限系统 采用SpringBoot2.0、MyBatis-Plus、Shiro框架,开发的一套权限系统 采用SpringBoot2.0、MyBatis-Plus、Shiro框架,开发的一套权限系统 采用...

    Ehcache分布式缓存与其在SpringBoot应用

    在SpringBoot应用中集成Ehcache,通常需要以下步骤: 1. **环境配置**:首先,你需要在SpringBoot的`pom.xml`文件中添加Ehcache和相关依赖。同时,在`application.properties`或`application.yml`文件中配置Ehcache...

    SpringBoot2.0整合Shiro框架实现用户权限管理的示例

    本文主要介绍了SpringBoot2.0整合Shiro框架实现用户权限管理的示例,通过详细的示例代码,展示了如何使用Shiro框架来实现用户权限管理。下面是对应的知识点: 1. Shiro简介:Shiro是一个强大且易用的Java安全框架,...

    springboot2.0+shiro+jwt+redis+swagger+layui+thymeleaf

    基于spring boot 2.1.6、shiro、jwt、redis、swagger2、mybatis 、thymeleaf、layui 后台管理系统, 权限控制的方式为 RBAC。代码通熟易懂 、JWT(无状态token)过期自动刷新,数据全程 ajax 获取,封装 ajax 工具类...

    SpringBoot中Shiro缓存使用Redis、Ehcache的方法

    主要介绍了SpringBoot中Shiro缓存使用Redis、Ehcache的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    springBoot2.0+mybatis支持多数据源+shiro

    本项目主题是"springBoot2.0+mybatis支持多数据源+shiro",这涉及到Java开发中的几个关键组件的集成与应用。 首先,让我们来详细了解一下这些技术: **SpringBoot 2.0**:这是Spring框架的一个子项目,旨在简化...

    springboot 1.5 集成 shiro 1.4

    SpringBoot 1.5 集成 Shiro 1.4 案例详解 SpringBoot 是一个基于 Spring 框架的简化启动工具,它提供了自动配置、内嵌服务器、依赖管理和运行时指标等功能,使得开发 Java 应用程序变得更加便捷。而 Apache Shiro ...

    SpringBoot2.0 Shiro MyBatisPlus权限管理系统.docx

    **SpringBoot2.0 Shiro MyBatisPlus 权限管理系统** 该项目是一个基于SpringBoot 2.0的后台管理系统,采用Shiro安全框架来实现权限控制。它利用了Shiro的强大功能,允许管理员为不同的角色设定不同的访问权限,从而...

    采用SpringBoot2.0、MyBatis、Redis缓存、Shiro权限管理、dr-niaobulashi.zip

    本项目"dr-niaobulashi"便是一个典型的例子,它利用了SpringBoot2.0、MyBatis、Redis缓存以及Shiro权限管理技术,构建了一个功能完善的后台管理系统。接下来,我们将深入探讨这些技术的核心概念及其在该项目中的应用...

    SpringBoot2整合shiro

    - **缓存集成**:Shiro可以与Guava、Ehcache等缓存系统结合,优化性能。 - **分布式环境**:在分布式环境中,可以使用Shiro的SessionManager和CacheManager集成Redis或Memcached来共享会话和权限信息。 - **Restful ...

    基于SpringBoot2+Shiro+Thymeleaf的后台管理系统.zip

    基于SpringBoot2+Shiro+Thymeleaf的后台管理系统 基于SpringBoot2+Shiro+Thymeleaf的后台管理系统 基于SpringBoot2+Shiro+Thymeleaf的后台管理系统 基于SpringBoot2+Shiro+Thymeleaf的后台管理系统 基于SpringBoot2+...

    基于SpringBoot2+Shiro+Thymeleaf的后台管理系统源码+数据库.zip

    【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,...基于SpringBoot2+Shiro+Thymeleaf的后台管理系统源码+数据库.zip

    基于SpringBoot2.0 + Spring Data Jpa + Thymeleaf + Shiro 开发的后台管理系统

    TIMO后台管理系统,基于SpringBoot2.0 + Spring Data Jpa + Thymeleaf + Shiro 开发的后台管理系统,采用分模块的方式便于开发和维护,支持前后台模块分别部署,目前支持的功能有:权限管理、部门管理、字典管理、...

    springboot-2.0-shiro.rar

    springboot与shiroShiro是Apache旗下的一个开源项目,它是一个非常易用的安全框架,提供了包括认证、授权、加密、会话管理等功能,与Spring Security一样属基于权限的安全框架,但是与Spring Security 相比,Shiro...

    SpringBoot 集成 Shiro 实现动态uri权限

    SpringBoot集成Shiro实现动态URI权限是一个常见的权限管理实践,主要目的是为了实现更灵活、更安全的用户访问控制。在Web应用中,权限控制通常包括角色管理、菜单管理、操作权限(URI)管理等,而动态URI权限则允许...

    SpringBoot集成Shiro、Jwt和Redis

    4. 集成Redis:配置Redis的连接池,设置Session的Redis序列化方式,并在Shiro配置中指定使用RedisSessionDAO。 5. 配置MyBatisPlus:设置数据库连接信息,创建Mapper接口和Mapper XML文件,编写Service和Controller...

    基于Springboot2.0的后台权限管理系统设计源码

    这个系统采用了前后端分离模式,使用了Springboot、Shiro、JWT、Redis、Layui、Thymeleaf、Swagger和Mybatis等技术。权限控制采用RBAC模型,代码易于理解和维护。此外,系统还支持JWT(无状态token)过期自动刷新和...

    springboot集成freemarker和shiro框架

    **SpringBoot集成Freemarker与Shiro框架详解** 在现代Web开发中,SpringBoot因其简洁、高效的特性,已经成为很多开发者的选择。而FreeMarker和Shiro则分别是常用的模板引擎和安全框架,它们能帮助我们构建出功能...

Global site tag (gtag.js) - Google Analytics