shiro的session和servlet的session的区别

shiro作为轻量级的权限管理框架,应用广泛。在使用过程中需要注意org.apache.shiro.web.session.mgt.DefaultWebSessionManager默认session是shiro原生(native)session,不同于servlet自身的session,在jsp页面获取不到session中的值。

一、shiro中session和servlet自身session区别

shiro默认session管理器是DefaultWebSessionManager ,DefaultWebSessionManager 实现自WebSessionManager,我们来看下WebSessionManager的的定义,只有一个方法isServletContainerSessions:

     /**
     * Returns {@code true} if session management and storage is managed by the underlying Servlet container or
     * {@code false} if managed by Shiro directly (called 'native' sessions).
     * <p/>
     * If sessions are enabled, Shiro can make use of Sessions to retain security information from
     * request to request.  This method indicates whether Shiro would use the Servlet container sessions to fulfill its
     * needs, or if it would use its own native session management instead (which can support enterprise features
     * - like distributed caching - in a container-independent manner).
     *
     * @return {@code true} if session management and storage is managed by the underlying Servlet container or
     *         {@code false} if managed by Shiro directly (called 'native' sessions).
     */
    boolean isServletContainerSessions();
翻译成中文主要意思就是:如果返回true,使用servlet容器的session,如果返回false,使用shiro自身的session(即native的)。使用shiro的session支持企业级的特性,例如分布式缓存。

我们再来看一下DefaultWebSessionManager 对isServletContainerSessions方法的实现:

 /**
     * This is a native session manager implementation, so this method returns {@code false} always.
     *
     * @return {@code false} always
     * @since 1.2
     */
    public boolean isServletContainerSessions() {
        return false;
    }
返回false,使用的是shiro自身的session。

二、shiro中使用servlet的session

如果我们想要使用servlet的session,需要做的就是(1)写一个类继承DefaultWebSessionManager ,复写isServletContainerSessions,返回true;(2)在shiro配置文件中使用自定义类。

1.自定义类MyWebSessionManager,继承DefaultWebSessionManager ,复写isServletContainerSessions方法

public class MyWebSessionManager extends DefaultWebSessionManager {

	@Override
	public boolean isServletContainerSessions() {
		return true;
	}

}

2.在shiro.xml配置文件使用自定义类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<description>spring-shiro</description>

	<bean id="defaultWebSessionManager"
		 class="com.bec.risk.controller.security.MyWebSessionManager">
		<!-- 3600000 = 1hour -->
		<property name="globalSessionTimeout" value="3600000" />
		<property name="sessionDAO" ref="sessionDAO" />
		<property name="sessionIdUrlRewritingEnabled" value="false" />
		<property name="sessionIdCookie.name" value="jsid" />
	</bean>

	<bean id="sessionDAO"
		class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
		<property name="activeSessionsCacheName" value="shiro-activeSessionCache" />
		<property name="cacheManager" ref="cacheManager" />
	</bean>

	<!-- 凭证匹配器 -->
	<bean id="credentialsMatcher"
		class="com.bec.risk.controller.security.RetryLimitHashedCredentialsMatcher">
		<constructor-arg ref="cacheManager" />
		<property name="hashAlgorithmName" value="md5" />
		<property name="hashIterations" value="3" />
		<property name="storedCredentialsHexEncoded" value="true" />
	</bean>

	<!-- 自定义的Realm数据源 -->
	<bean id="shiroDbRealm" class="com.bec.risk.controller.security.ShiroDbRealm">
		<property name="cachingEnabled" value="true" />
		<property name="authenticationCachingEnabled" value="true" />
		<property name="authenticationCacheName" value="shiroAuthenticationCache" />
		<property name="authorizationCachingEnabled" value="true" />
		<property name="authorizationCacheName" value="shiroAuthorizationCache" />
		<property name="credentialsMatcher" ref="credentialsMatcher" />
	</bean>

	<!-- Shiro's main business-tier object for web-enabled applications -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="shiroDbRealm" />
		<property name="cacheManager" ref="cacheManager" />
		<property name="sessionManager" ref="defaultWebSessionManager" />
	</bean>

	<bean id="casFilter"
		class="com.bec.risk.controller.security.MyFormAuthenticationFilter" />

	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<property name="loginUrl" value="/login" />
		<property name="successUrl" value="/view/index" />
		<property name="unauthorizedUrl" value="/403" />
		<property name="filters">
			<map>
				<entry key="authc" value-ref="casFilter" />
			</map>
		</property>
		<!-- shiro连接约束配置 -->
		<property name="filterChainDefinitions">
			<!-- anon 匿名过滤器 authc 如果继续操作,需要做对应的表单验证否则不能通过 authcBasic 基本http验证过滤,如果不通过,跳转到登录页面 
				logout 登录退出过滤器 noSessionCreation 没有session创建过滤器 perms 权限过滤器 port 端口过滤器,可以设置是否是指定端口如果不是跳转到登录页面 
				rest http方法过滤器,可以指定如post不能进行访问等 roles 角色过滤器,判断当前用户是否指定角色 ssl 请求需要通过ssl,如果不是跳转回登录页 
				user 如果访问一个已知用户,比如记住我功能,走这个过滤器 -->
			<value>
				/swagger-ui.html=authc
				/kaptcha = anon
				/login=authc
				/logout=logout
				/assets/** = anon
				/static/** = anon
				/interface/** = anon
				/**=authc
			</value>
		</property>
	</bean>

	<!-- 缓存管理器 使用Ehcache实现 -->
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache.xml" />
	</bean>

	<!-- Shiro生命周期处理器 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

	<!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
	<!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" 
		depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" 
		value="true" /> </bean> -->
	<bean
		class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>

</beans>


使用到了ehcache缓存,虽然和本主题无关,为方便大家测试,将ehcache.xml配置也贴在下方

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="risk-ehcache">
	<diskStore path="java.io.tmpdir" />
	<!-- DefaultCache setting. -->
	<defaultCache maxEntriesLocalHeap="10000" eternal="true"
		timeToIdleSeconds="12000" timeToLiveSeconds="12000" 
		overflowToDisk="false" diskPersistent="false" maxEntriesLocalDisk="100000" />
	<cache name="passwordRetryCache" maxElementsInMemory="20000"
		maxEntriesLocalHeap="10000" eternal="false"
		timeToIdleSeconds="12000" timeToLiveSeconds="12000"
		overflowToDisk="false" diskPersistent="false" 
		memoryStoreEvictionPolicy="LRU" statistics="true">
	</cache>
	<cache name="shiro-activeSessionCache"
           maxElementsInMemory="30000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="12000"
           timeToLiveSeconds="0"
           diskPersistent="false"
           memoryStoreEvictionPolicy="LRU"  /> 
    <cache name="shiroAuthenticationCache"
           maxElementsInMemory="30000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           diskPersistent="false"
           memoryStoreEvictionPolicy="LRU"  /> 
    <cache name="shiroAuthorizationCache"
           maxElementsInMemory="30000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="12000"
           timeToLiveSeconds="0"
           diskPersistent="false"
           memoryStoreEvictionPolicy="LRU"  /> 
</ehcache>


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值