设为首页 收藏本站
查看: 471|回复: 0

[经验分享] 基于Spring框架Web应用程序Apache Shiro配置

[复制链接]

尚未签到

发表于 2017-1-9 11:07:12 | 显示全部楼层 |阅读模式
  一、在web.xml中添加shiro过滤器

<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>*.do</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>*.htm</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>*.json</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
  二、在Spring的applicationContext.xml中添加shiro配置
  1、sessionManger 会话管理


<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="globalSessionTimeout" value="3600000" />
<property name="sessionValidationSchedulerEnabled" value="false" />
<property name="deleteInvalidSessions" value="false" />
<property name="sessionDAO">
<bean class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="activeSessionsCacheName" value="activeSessionCache" />
</bean>
</property>
</bean>
  2、credentialsMatcher 密码加密


<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA-256" />
<!-- true means hex encoded, false means base64 encoded -->
<property name="storedCredentialsHexEncoded" value="false" />
</bean>


3、自定义Realm
<bean id="dbRealm" class="com.chuanlu.family.shiro.DbRealm">
<property name="credentialsMatcher" ref="credentialsMatcher" />
<property name="cacheManager" ref="cacheManager" />
</bean>
  4、securityManager


<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realms">
<list>
<ref local="dbRealm" />
</list>
</property>
<!-- 此属性如果不配置,程序会创建默认Servlet容器会话 -->
<property name="sessionManager" ref="sessionManager" />
<!-- 此属性也可以配其他第三方缓存,如Memcached。如果不配置,则无法完成分布式集群,但不影响本地运行。-->
<property name="cacheManager" ref="cacheManager" />
</bean>
  5、shiroFilter

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login.htm" />
<property name="successUrl" value="/index.htm" />
<property name="unauthorizedUrl" value="/login.htm" />
<property name="filters">
<util:map>
<entry key="ssl">
<bean class="org.apache.shiro.web.filter.authz.SslFilter">
<property name="enabled" value="${ssl.enabled}" />
</bean>
</entry>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/login.htm = noSessionCreation, ssl[443]
/login.do = anon
/* = user
</value>
</property>
</bean>
  6、shiro注解支持

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.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>
  三、Ehcache配置

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!--
DiskStore configuration
=======================
The diskStore element is optional. To turn off disk store path creation, comment out the diskStore element below.
Configure it if you have overflowToDisk or diskPersistent enabled for any cache.
If it is not configured, and a cache is created which requires a disk store, a warning will be issued and java.io.tmpdir will automatically be used.
diskStore has only one attribute - "path". It is the path to the directory where .data and .index files will be created.
If the path is one of the following Java System Property it is replaced by its value in the running VM. For backward compatibility these should be specified without being enclosed in the ${token} replacement syntax.
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
* ehcache.disk.store.dir - A system property you would normally specify on the command line
e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...
Subdirectories can be specified below the property e.g. java.io.tmpdir/one
-->
<diskStore path="java.io.tmpdir" />
<!--
Mandatory Default Cache configuration. These settings will be applied to cachescreated programmtically using CacheManager.add(String cacheName).
The defaultCache has an implicit name "default" which is a reserved cache name.
-->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120"
overflowToDisk="true" diskPersistent="false"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
<!--
Cache configuration
===================
The following attributes are required.
name:
Sets the name of the cache. This is used to identify the cache. It must be unique.
maxElementsInMemory:
Sets the maximum number of objects that will be created in memory.  0 == no limit.
maxElementsOnDisk:
Sets the maximum number of objects that will be maintained in the DiskStore
The default value is zero, meaning unlimited.
eternal:
Sets whether elements are eternal. If eternal,  timeouts are ignored and the
element is never expired.
overflowToDisk:
Sets whether elements can overflow to disk when the memory store has reached the maxInMemory limit.
The following attributes and elements are optional.
timeToIdleSeconds:
Sets the time to idle for an element before it expires.
i.e. The maximum amount of time between accesses before an element expires
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that an Element can idle for infinity.
The default value is 0.
timeToLiveSeconds:
Sets the time to live for an element before it expires.
i.e. The maximum time between creation time and when an element expires.
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that and Element can live for infinity.
The default value is 0.
diskPersistent:
Whether the disk store persists between restarts of the Virtual Machine.
The default value is false.
diskExpiryThreadIntervalSeconds:
The number of seconds between runs of the disk expiry thread. The default value is 120 seconds.
diskSpoolBufferSizeMB:
This is the size to allocate the DiskStore for a spool buffer. Writes are made to this area and then asynchronously written to disk. The default size is 30MB.
Each spool buffer is used only by its cache. If you get OutOfMemory errors consider lowering this value. To improve DiskStore performance consider increasing it. Trace level logging in the DiskStore will show if put back ups are occurring.
clearOnFlush:
whether the MemoryStore should be cleared when flush() is called on the cache.
By default, this is true i.e. the MemoryStore is cleared.
memoryStoreEvictionPolicy:
Policy would be enforced upon reaching the maxElementsInMemory limit. Default
policy is Least Recently Used (specified as LRU). Other policies available -
First In First Out (specified as FIFO) and Less Frequently Used
(specified as LFU)
-->
<cache name="cacheManager" maxElementsInMemory="10000"
eternal="false" overflowToDisk="false"
timeToIdleSeconds="60"
timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU" />
</ehcache>

  三、自定义Realm类


/**
* chuanlu
*/
package com.chuanlu.family.shiro;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import com.chuanlu.family.dao.UserDao;
import com.chuanlu.family.pojo.User;
/**
* DbRealm
*
* @作者 宋陆
* @日期 2013年10月5日
* @版本 1.0
*/
public class DbRealm extends AuthorizingRealm {
@Resource
private UserDao userDao;
/**
* @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 授权信息
Set<String> roleNames = new LinkedHashSet<String>();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
return info;
}
/**
* @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 认证信息
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String userName = upToken.getUsername();
SimpleAuthenticationInfo info = null;
User user = userDao.getUserByUserName(userName);
if (user != null) {
String pwd = user.getPassword();
String pwdSalt = user.getPwdSalt();
info = new SimpleAuthenticationInfo(user.getUserId(), pwd.toCharArray(), getName());
info.setCredentialsSalt(ByteSource.Util.bytes(pwdSalt));
}
return info;
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-325944-1-1.html 上篇帖子: Windows下 apache 和 tomcat的 负载均衡 下篇帖子: windowsXP下配置apache+perl的运行环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表