备注:文中配置基本来自尚硅谷视频教程,也可自行参照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. MetaWeblog是什么

    MetaWebBlog API(MWA)是一个Blog程序接口标准,允许外部程序来获取或者设置Blog的文字和熟悉.他建立在XMLRPC接口之上,并且已经有了很多的实现. 所以现在很多博客系统都支持这 ...

  2. 敏捷开发中的sprint是什么意思_百度知道

    敏捷开发中的sprint是什么意思_百度知道     敏捷开发中的sprint是什么意思    未成年RB21 | 浏览 4208 次    推荐于2016-02-27 15:19:02     最佳 ...

  3. IDEA中添加类的创建者信息

    创建方法: 1. 使用快捷键(ctrl + alt + s),在弹出框中左边侧选择 Editor -> File and Code Templates,左边侧相应会更新 右边侧选择 Class, ...

  4. Ueditor .net版安装配置打开项目的源码傻瓜版教程 亲測~

    环境要求: 没有 .NET Framework 4.0的要先安装 安装完 .NET Framework 4.0 后.还须要向 IIS 注冊应用程序池,注冊的方法是,使用管理员权限打开命令提示符(CMD ...

  5. Druid对比Cassandra

    不是Cassandra专家, 如果描绘有错误, 请通过邮件列表或者其他方式告知, 我们会修正. Druid对扫描和聚合做了很大程度的优化, 不用提前计算就支持任意的向下钻取, 还可以实时摄入流式数据并 ...

  6. druid.io使用技术简介: Hyperloglog

    druid.io 使用Hyperloglog 估计基数 参照如下连接 http://blog.codinglabs.org/articles/algorithms-for-cardinality-es ...

  7. 在 Word 中的受支持的区域设置标识符的列表

    这篇文章包含当前可用的区域设置 ID (LCID) 语言代码的列表.   概要 这篇文章包含当前可用的区域设置 ID (LCID) 语言代码的列表. 区域设置 ID (LCID): 由 Microso ...

  8. nmap小技巧[1] 探测大网络空间中的存活主机

    url: nmap是所有安全爱好者应该熟练掌握的扫描工具,本篇介绍其在扫描大网络空间时的用法. 为什么要扫描大网络空间呢? 有这样的情形: 内网渗透   攻击者单点突破,进入内网后,需进一步扩大成果, ...

  9. 微信小程序 - 表单验证插件WxValidate(自定义警告信息形式)

    弹出的形式对于用户来说,总是不太友好的 可能会出现层级问题(只需要设置一下提示的层级即可) WxValidate内置规则 以下代码拷贝即可使用~ wxml <form bindsubmit='s ...

  10. python列表解析和正同表达式

    正则表达式 [i for i in ['1232','233','22'] if re.match('^233$', i)]   return  ['233']