当前位置:首页 > 开发 > 编程语言 > Spring > 正文

基于Spring框架Web应用程序Apache Shiro配置

发表于: 2013-10-07   作者:songchuanlu   来源:转载   浏览次数:
摘要: 一、在web.xml中添加shiro过滤器   <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <

一、在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;
    }

}

 

基于Spring框架Web应用程序Apache Shiro配置

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
在 Web 项目中应用 Apache Shiro 开源权限框架 发布时间:2013-02-06 14:51:56 来源: 评论:0 点击
在 Web 项目中应用 Apache Shiro 开源权限框架 发布时间:2013-02-06 14:51:56 来源: 评论:0 点击
shiro是一个很不错的安全框架,相对Spring security 来说要简单易用的多,使用shiro来做web的权限子
shiro是一个很不错的安全框架,相对Spring security 来说要简单易用的多,使用shiro来做web的权限子
Shiro可以和普通web集成的,但考虑到现在的应用基本都会使用spring,所以就不去讲最基本的web集成了
前几天一时兴起,看到一个基于RESTful web Service的很不错的框架 jersey .并且做了一个小小的案例.
原文 ;http://www.ibm.com/developerworks/cn/java/j-lo-shiro/index.html Apache Shiro 是功能强
ApacheShiro 是功能强大并且容易集成的开源权限框架,它能够完成认证、授权、加密、会话管理等功能
Apache Shiro 是功能强大并且容易集成的开源权限框架,它能够完成认证、授权、加密、会话管理等功能
在 Web 项目中应用 Apache Shiro Apache Shiro 是功能强大并且容易集成的开源权限框架,它能够完成认
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号