springMVC集成 -- shiro(配置)
备注:文中配置基本来自尚硅谷视频教程,也可自行参照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(配置)的更多相关文章
- springmvc集成shiro登录失败处理
一般的登录流程会有:用户名不存在,密码错误,验证码错误等.. 在集成shiro后,应用程序的外部访问权限以及访问控制交给了shiro来管理. shiro提供了两个主要功能:认证(Authenticat ...
- springmvc集成shiro后,session、request是否发生变化
1. 疑问 我们在项目中使用了spring mvc作为MVC框架,shiro作为权限控制框架,在使用过程中慢慢地产生了下面几个疑惑,本篇文章将会带着疑问慢慢地解析shiro源码,从而解开心里面的那点小 ...
- SpringMVC集成Shiro、读取数据库操作权限
1.Maven添加Shiro所需的jar包 <dependency> <groupId>org.apache.shiro</groupId> <artifac ...
- springmvc集成Freemarke配置的几点
项目结构图 废话不多说, 集成步骤: 1.web.xml spring-mvc配置 <?xml version="1.0" encoding="UTF-8&quo ...
- 【实用小技巧】spring springmvc集成shiro时报 No bean named 'shiroFilter' available
查了网上的,很多情况,不同的解决办法,总归一点就是配置文件加载的问题. 先看下配置文件中的配置 web.xml中的主要配置(这是修改后不在报错的:仅仅修改了一个位置:[classpath:spring ...
- springmvc集成shiro例子
仅供参考 仅供参考 登录部分 代码: @RequestMapping(value = "/login", method = RequestMethod.GET) @Response ...
- spring-mvc集成 swagger
问题1:spring-mvc集成 swagger, 配置好后界面 404, 原因: dispatcher-servlet.xml 文件中, 要在这上面 <!-- 启用spring mvc 注解 ...
- 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 ...
- SpringMVC+Apache Shiro+JPA(hibernate)整合配置
序: 关于标题: 说是教学,实在愧不敢当,但苦与本人文笔有限,实在找不到更合理,谦逊的词语表达,只能先这样定义了. 其实最真实的想法,只是希望这个关键词能让更多的人浏览到这篇文章,也算是对于自己写文章 ...
随机推荐
- a + b ——C语言初学者百题大战之四
#include <stdio.h> int main() { int a,b; scanf("%d %d",&a,&b); printf(" ...
- FCL研究-LINQ-System.Linq Enumerable
.net 里面集合操作极为方便,尤其是实现了IEnumerable接口的集合,一直在使用,系统的研究一下集合的操作也是极好的. 类型 操作符名称 投影操作符 Select,SelectMany 限制操 ...
- JQurey中getJSON方法错误回调方法
1.使用try...catch实现 2.换$.ajax 3.JQuery 1.5+可以这样使用: $.getJSON("example.json", function() { al ...
- 继续推荐几款VisualStudio的插件(二)
今天晚上闲着的时候逛了一下,发现了几款不错的VisualStudio插件,这里推荐一下: Exception Breaker 在调试的时候,为了及时发现错误,我们常常会打开"总是引发所有CL ...
- 阿里p6面试
电话面试: 第一次面试关注的问题,1)java基础: jvm 内存回收,垃圾回收基本原理,Java并发包的线程池,Java8的新特性.nio 堆排序.conrenthashmap , concurre ...
- linux下目录大小为什么是4K?一个目录下最多有个多少个子目录?最多有多少个文件?ls -l显示的内容中total到底是什么?
子目录数太多,会影响搜索性能. 在同一个路径下,一级子目录的个数限制为31998,如果你的应用生成的目录可能会超过这个数,那要注意进行目录分级.例如,如果目录名为数字的话,可以将数字除以10000后的 ...
- delphi 接口Interface
学习 delphi 接口 一切都是纸老虎!!! 第四章 接口 前不久,有位搞软件的朋友给我出了个谜语.谜面是“相亲”,让我猜一软件术语.我大约想了一分钟,猜 出谜底是“面向对象”.我 ...
- http://zhidao.baidu.com/link?url=3tJ_i5gyYLrd7rFPk0eRYre_oxjCZvTOMOutp89LGhUgi6Ic6Ncama_GMAHnwfF73SVYGqy364vDfv6AY4ERPa
http://zhidao.baidu.com/link?url=3tJ_i5gyYLrd7rFPk0eRYre_oxjCZvTOMOutp89LGhUgi6Ic6Ncama_GMAHnwfF73SV ...
- Unity3D之高级渲染-Shader Forge增强版
笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家.特邀编辑.畅销书作者,国家专利发明人;已出版书籍:<手把手教你架构3D游戏引擎>电子工业出版社和<Unity3D ...
- Java线程:概念与原理(转)
一.操作系统中线程和进程的概念 现在的操作系统是多任务操作系统.多线程是实现多任务的一种方式. 进程是指一个内存中运行的应用程序,每个进程都有自己独立的一块内存空间,一个进程中可以启动多个线程.比如在 ...