备注:文中配置基本来自尚硅谷视频教程,也可自行参照shiro官方教程:http://shiro.apache.org/spring.html

1、首先通过maven导入shiro相关依赖jar包,修改pom.xml文件

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.2</version>
</dependency>

2、修改web.xml文件,添加如下内容

<!-- Shiro Filter is defined in the spring application context: -->
<!--
. 配置 Shiro 的 shiroFilter.
. DelegatingFilterProxy 实际上是 Filter 的一个代理对象. 默认情况下, Spring 会到 IOC 容器中查找和
<filter-name> 对应的 filter bean. 也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id.
-->
<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配置文件applicationcontext.xml,配置如下bean:

<!-- 1. 配置 SecurityManager  -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"></property>
<!-- 单个realm情况 -->
<!-- <property name="realm" ref="myRealm" /> -->
<!-- 多个realm情况 -->
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<!--shiro记住我功能的保存时间(秒)-->
<property name="rememberMeManager.cookie.maxAge" value=""></property>
</bean> <!-- . 配置 CacheManager.
2.1 需要加入 ehcache 的 jar 包及配置文件,此处shiro-all.jar已包含.
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- Set a net.sf.ehcache.CacheManager instance here if you already have one. If not, a new one
will be creaed with a default config:
<property name="cacheManager" ref="ehCacheManager"/> -->
<!-- If you don't have a pre-built net.sf.ehcache.CacheManager instance to inject, but you want
a specific Ehcache configuration to be used, specify that here. If you don't, a default
will be used.: -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>

  <!-- <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" /> -->

<!-- 配置多Realm认证策略 -->
<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean> <!--
. 配置 Realm
3.1 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean
-->
<bean id="jdbcRealm" class="com.atguigu.shiro.realms.ShiroRealm">
<!-- MD5加密 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value=""></property>
</bean>
</property>
</bean> <bean id="secondRealm" class="com.atguigu.shiro.realms.SecondRealm">
<!-- SHA1加密 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value=""></property>
</bean>
</property>
</bean> <!-- . 配置 LifecycleBeanPostProcessor. 可以自动的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法. -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- . 配置 ShiroFilter.
5.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/list.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/> <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property> <!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
). anon 可以被匿名访问
). authc 必须认证(即登录)后才可能访问的页面.
). logout 登出.
). roles 角色过滤器
-->
<!--
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout /user.jsp = roles[user]
/admin.jsp = roles[admin] # everything else requires authentication:
/** = authc
</value>
</property>
-->
</bean>

4、修改springMVC配置文件spring-mvc.xml,添加如下内容

<!--
启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用.
-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>

5、添加ehcache.xml配置文件到classpath下:

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
its value in the running VM. The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/> <cache name="authorizationCache"
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="false"
statistics="true">
</cache> <cache name="authenticationCache"
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="false"
statistics="true">
</cache> <cache name="shiro-activeSessionCache"
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="false"
statistics="true">
</cache> <!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. -->
<defaultCache
maxElementsInMemory=""
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="true"
/> <!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts The following attributes are required for defaultCache: name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. --> <!-- Sample cache named sampleCache1
This cache contains a maximum in memory of elements, and will expire
an element if it is idle for more than minutes and lives for more than
minutes. If there are more than elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory=""
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="true"
/> <!-- Sample cache named sampleCache2
This cache contains elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory=""
eternal="true"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="false"
/> --> <!-- Place configuration for your caches following --> </ehcache>

此处附上realm的一个实现ShiroRealm.java:

通常为了完成认证、授权,realm需继承自AuthorizingRealm

package com.atguigu.shiro.realms;

import java.util.HashSet;
import java.util.Set; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource; public class ShiroRealm extends AuthorizingRealm { @Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[FirstRealm] doGetAuthenticationInfo"); //1. 把 AuthenticationToken 转换为 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token; //2. 从 UsernamePasswordToken 中来获取 username
String username = upToken.getUsername(); //3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息."); //4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
if("unknown".equals(username)){
throw new UnknownAccountException("用户不存在!");
} //5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常.
if("monster".equals(username)){
throw new LockedAccountException("用户被锁定");
} //6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
//以下信息是从数据库中获取的.
//1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象.
Object principal = username;
//2). credentials: 密码.
Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
if("admin".equals(username)){
credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
}else if("user".equals(username)){
credentials = "098d2c478e9c11555ce2823231e02ec1";
} //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
String realmName = getName();
//4). 盐值.
ByteSource credentialsSalt = ByteSource.Util.bytes(username); SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);
info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return info;
} public static void main(String[] args) {
String hashAlgorithmName = "MD5";
Object credentials = "123456";
Object salt = ByteSource.Util.bytes("user");;
int hashIterations = 1024; Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(result);
} //授权会被 shiro 回调的方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
//1. 从 PrincipalCollection 中来获取登录用户的信息
Object principal = principals.getPrimaryPrincipal(); //2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库)
Set<String> roles = new HashSet<>();
roles.add("user");
if("admin".equals(principal)){
roles.add("admin");
} //3. 创建 SimpleAuthorizationInfo, 并设置其 reles 属性.
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
//也可通过info.addStringPermission(url);实现基于Permission的权限信息
//4. 返回 SimpleAuthorizationInfo 对象.
return info;
}
}

  

springMVC集成 -- shiro(配置)的更多相关文章

  1. springmvc集成shiro登录失败处理

    一般的登录流程会有:用户名不存在,密码错误,验证码错误等.. 在集成shiro后,应用程序的外部访问权限以及访问控制交给了shiro来管理. shiro提供了两个主要功能:认证(Authenticat ...

  2. springmvc集成shiro后,session、request是否发生变化

    1. 疑问 我们在项目中使用了spring mvc作为MVC框架,shiro作为权限控制框架,在使用过程中慢慢地产生了下面几个疑惑,本篇文章将会带着疑问慢慢地解析shiro源码,从而解开心里面的那点小 ...

  3. SpringMVC集成Shiro、读取数据库操作权限

    1.Maven添加Shiro所需的jar包 <dependency> <groupId>org.apache.shiro</groupId> <artifac ...

  4. springmvc集成Freemarke配置的几点

    项目结构图 废话不多说, 集成步骤: 1.web.xml  spring-mvc配置 <?xml version="1.0" encoding="UTF-8&quo ...

  5. 【实用小技巧】spring springmvc集成shiro时报 No bean named 'shiroFilter' available

    查了网上的,很多情况,不同的解决办法,总归一点就是配置文件加载的问题. 先看下配置文件中的配置 web.xml中的主要配置(这是修改后不在报错的:仅仅修改了一个位置:[classpath:spring ...

  6. springmvc集成shiro例子

    仅供参考 仅供参考 登录部分 代码: @RequestMapping(value = "/login", method = RequestMethod.GET) @Response ...

  7. spring-mvc集成 swagger

    问题1:spring-mvc集成 swagger, 配置好后界面 404, 原因: dispatcher-servlet.xml 文件中, 要在这上面 <!-- 启用spring mvc 注解 ...

  8. springmvc+spring+mybatis+maven项目集成shiro进行用户权限控制【转】

    项目结构:   1.maven项目的pom中引入shiro所需的jar包依赖关系 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...

  9. SpringMVC+Apache Shiro+JPA(hibernate)整合配置

    序: 关于标题: 说是教学,实在愧不敢当,但苦与本人文笔有限,实在找不到更合理,谦逊的词语表达,只能先这样定义了. 其实最真实的想法,只是希望这个关键词能让更多的人浏览到这篇文章,也算是对于自己写文章 ...

随机推荐

  1. 友情链接&部分题目的密码

    YPL: https://www.cnblogs.com/Sdchr/ ZWL: https://www.cnblogs.com/acha XJ: https://blog.csdn.net/boyx ...

  2. nativeexcel将excel导入数据集

    nativeexcel将excel导入数据集 uses nexcel; procedure Tfgoods.daoruExecute(Sender: TObject);var od: TOpenDia ...

  3. es6类声明,class总结

    1.class的基本写法 class a{ // 传入参数或者写入固定参数 constructor(a,b){ this.a=a this.b=b } // 可直接调用的计算后的参数 get c(){ ...

  4. springBoot框架的一些概念

    Spring的发展史1. Spring1.x 时代 在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml ...

  5. final修饰符的三种使用场景

    final有三种使用场景,各自是修饰变量.方法和类.不管哪种修饰.一旦声明为final类型.你将不能改变这个引用了,编译器会检查代码,假设你试图再次初始化,编译器会报错.以下我来详细说说每一种修饰场景 ...

  6. OpenStack手动制作CentOS 7 KVM镜像

    在前面讲解KVM的时候,我们已经学习了如何制作KVM镜像,那么制作OpenStack使用的镜像和KVM是有一些区别的. 1.    下载CentOS 7官方ISO安装镜像这里使用国内阿里云的镜像源进行 ...

  7. ubuntu16.04 登录密码破解方法

    1:开机按Shift键,出现如下界面.(手速要快,Shift键要按时间久一点) 选择第二项 2:按回车键进入如下界面,然后选中有recovery mode的选项(第三项) 3:按e进入如下界面,并找到 ...

  8. [GitHub开源]基于HTML5实现的轻量级Google Earth三维地图引擎,带你畅游世界 【转】

    http://blog.csdn.net/iispring/article/details/52679185 WebGlobe HTML5基于原生WebGL实现的轻量级Google Earth三维地图 ...

  9. http://blog.csdn.net/jhg1204/article/details/45013987

    http://blog.csdn.net/jhg1204/article/details/45013987

  10. Solr6.6.0 用 SimplePostTool与界面dataimport索引方式区别

    通过测试发现用SimplePostTool与solr界面dataimport索引数据的结果有如下区别: 1.SimplePostTool索引数据对结构化数据文件索引比较合适,比如csv/json/xm ...