1、向spring项目中添加shiro相关的依赖

        <dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.8</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>

2、在web.xml配置ShiroFilter

<!-- shiro过虑器,DelegatingFilterProx会从spring容器中找shiroFilter -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3、建立一个 spring 的配置文件 spring-shiro.xml

  a、使用 import 标签把此文件引入为spring的配置文件

<import resource="classpath:spring-shiro.xml"></import>

  b、配置spring-shiro.xml文件

    <!-- shiro 拦截器配置 -->
<!-- ShiroFilter 名字必须要和web.xml中配置的名字一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="unauthorizedUrl" value="/nopermission.jsp"/>
<!-- filterChainDefinitions 相当于.ini文件中的[urls] -->
<property name="filterChainDefinitions">
<value>
/logout=logout
/**=authc
</value>
</property>
</bean>
<!--shiro权限异常处理 -->
<!-- 上面对“/nopermission.jsp”的配置不会生效,因为 spring 默认会抛出异常到页面;需要添加下面这个配置才可以生效-->
<!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常页名作为值 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/nopermission.jsp</prop>
</props>
</property>
</bean> <!-- 配置安全管理器SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<!-- 给shiro添加缓存配置 -->
<property name="cacheManager" ref="cacheManager"></property>
</bean>
<!-- 配置自定义的Realm -->
<bean id="userRealm" class="cn.wolfcode.shiro.realm.UserRealm">
<!-- 加密器 -->
<property name="credentialsMatcher" ref="credentialsMatcher" />
</bean>
<!-- 在自定义的realm那个类里还要指定盐 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法 -->
<property name="hashAlgorithmName" value="md5" />
<!-- 散列次数 -->
<property name="hashIterations" value="3" />
</bean> <!-- 开启aop,对类代理;并开启shiro注解支持 -->
<aop:config proxy-target-class="true"></aop:config>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean> <!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:shiro-ehcache.xml" />
<property name="shared" value="true"></property>
</bean>

4、实现自己的realm

public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return "UserRealm";
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
if(!"admin".equals(principal)){
return null;
}
Employee currentUser = new Employee();
currentUser.setName(principal);
currentUser.setPassword("1");
currentUser.setAdmin(true);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),getName());
return authenticationInfo;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Employee currentUser = (Employee) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
List<String> roles = new ArrayList<String>();
roles.addAll(Arrays.asList("HR MGR","ORDER MGR"));
authorizationInfo.addRoles(roles);
List<String> perms = new ArrayList<String>();
perms.addAll(Arrays.asList("employee:view","employee:delete"));
authorizationInfo.addStringPermissions(perms);
return authorizationInfo;
}
}

5、 实现登陆方法

Suject 会自动创建,不需要我们配置;相应的登陆方法也会自动调用,不需要我们写。

    //此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
@RequestMapping("/login")
public String login(Model model, HttpServletRequest req) throws Exception{
//如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
//根据shiro返回的异常类路径判断,抛出指定异常信息
if(exceptionClassName!=null){
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//最终会抛给异常处理器 model.addAttribute("errorMsg", "账号不存在");
} else if (IncorrectCredentialsException.class.getName().equals(
exceptionClassName)) {
model.addAttribute("errorMsg", "用户名/密码错误");
} else {
//最终在异常处理器生成未知错误.
model.addAttribute("errorMsg", "其他异常信息");
}
}
//登陆失败还到login页面
return "forward:/login.jsp";
}

6、缓存管理(登陆时把当前用户的权限缓存起来,之后不需要再次查询)

  a、添加依赖

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.8</version>
</dependency>

  b、securityManager引用缓存管理器(如上)

  c、配置缓存管理器,并指定缓存框架配置文件路径(如上)

    ehcache版本在2.5.0以下,需要配置如下:
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
      <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"></property>
    </bean>
    ehcache版本在2.5.0以上,需要配置如下:
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
      <property name="cacheManager" ref="ehCacheManager"/>
    </bean>
    <bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
      <property name="configLocation" value="classpath:shiro-ehcache.xml" />
      <property name="shared" value="true"></property>
    </bean>

  d、配置 shiro-ehcache.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

7、清除缓存

  如果用户正常退出,缓存自动清空;如果用户非正常退出,缓存自动清空。

  如果修改了用户的权限,而用户不退出系统,修改的权限无法立即生效;用户退出并再次登陆系统时,shiro会自动调用realm从数据库重新获取权限数据,才会使修改的权限得以生效。

  如果在修改权限后想要立即生效,需要清除缓存,可以调用realm的clearCache方法。

// 在realm中定义该方法,在角色或权限service中,delete或者update方法里来调用
// 清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}

spring shiro 集成的更多相关文章

  1. 十一、Spring Boot 集成Shiro和CAS

    1.Shiro 是什么?怎么用? 2.Cas 是什么?怎么用? 3.最好有spring基础 首先看一下下面这张图: 第一个流程是单纯使用Shiro的流程. 第二个流程是单纯使用Cas的流程. 第三个图 ...

  2. spring中集成shiro

    Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用Spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成. 在示 ...

  3. Spring Boot 集成Shiro和CAS

    Spring Boot 集成Shiro和CAS 标签: springshirocas 2016-01-17 23:03 35765人阅读 评论(22) 收藏 举报  分类: Spring(42)  版 ...

  4. 解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题

    如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天 ...

  5. Spring Boot集成Shiro实战

    Spring Boot集成Shiro权限验证框架,可参考: https://shiro.apache.org/spring-boot.html 引入依赖 <dependency> < ...

  6. cas+tomcat+shiro实现单点登录-4-Apache Shiro 集成Cas作为cas client端实现

    目录 1.tomcat添加https安全协议 2.下载cas server端部署到tomcat上 3.CAS服务器深入配置(连接MYSQL) 4.Apache Shiro 集成Cas作为cas cli ...

  7. Spring项目集成ShiroFilter简单配置

    Shiros是我们开发中常用的用来实现权限控制的一种工具包,它主要有认证.授权.加密.会话管理.与Web集成.缓存等功能.我是从事javaweb工作的,我就经常遇到需要实现权限控制的项目,之前我们都是 ...

  8. spring-boot-2.0.3应用篇 - shiro集成

    前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...

  9. Shiro集成web环境[Springboot]-基础使用

    Shiro集成web环境[Springboot] 1.shiro官网查找依赖的jar,其中shiro-ehcache做授权缓存时使用,另外还需要导入ehcache的jar包 <dependenc ...

随机推荐

  1. MVC的默认约定

    MVC项目中有很多默认约定,一种是对项目目录分配的约定,比如默认情况下需要将Javascript文件放置在Script文件夹中,但这并不妨碍你将这个文件夹重新命名,也可以将整个文件夹放置到任何想要放置 ...

  2. EJB3 阶段总结+一个EJB3案例 (1)

    经过一段时时间的学习,对EJB3的相关知识和jboss8的配置有了大概的了解. 网上对EJB的评论很多,基本都是负面的,都表示EJB太过于沉重,不容易维护.但通过这段时间的学习,私下认为,EJB3在某 ...

  3. 模板模式(TemplateMethod)

    什么是Template Method模式 在父类中定义处理流程的框架,在子类中实现具体处理的模式就称为Template Mehtod模式.模板模式的关键是:子类可以置换掉父类的可变部分,但是子类却不可 ...

  4. 数字和表达式(python)

    >>>2+2 4 >>>1/2#(注:3.0版本之前是这样的,整数除法) >>>1.0/2.0 0.5 >>>1.0/2 0.5 ...

  5. 删除none 的images报错 image has dependent child images 解决办法

    这个错是因为在要删除的images之后创建了该images的父images 方法: docker image inspect --format='{{.RepoTags}} {{.Id}} {{.Pa ...

  6. php发送get请求

    感谢:http://www.zoneself.org/2014/07/21/content_2665.html 1.用PHP发送get请求,很简单: <?php $url='http://www ...

  7. Velocity学习笔记

    一.为什么要使用velocity? 很多人下载了EasyJWeb的开源应用示例,但是对动态页面模板文件中的标签使用不是很熟悉,这里简单介绍一下.EasyJWeb特定把视图限定为Velocity,因为我 ...

  8. 【LeetCode题解】141_环形链表

    目录 141_环形链表 描述 解法一:哈希表 思路 Java 实现 Python 实现 解法二:双指针(龟兔算法) 思路 Java 实现 Python 实现 141_环形链表 描述 给定一个链表,判断 ...

  9. 既之前的基础,先写个简单的PHP 与数据库 的数据交流

    程序分三个板块, 现在先不用 css 和 javascript     先用纯 html  php  写吧. 所以那些 嵌入式 <font  size=....  什么的看看就算了,不推荐如此使 ...

  10. 4.1 SQL的本质

    对于早期的关系数据库,整个行业做了很多努力,试图统一不同的专用查询语言.IBM曾建立了一个早期的标准,被称为Structured English Query Language,这个名字缩写为SEQUE ...