站点图标 江湖人士

shiro安全框架异常退出没有清除缓存信息处理方案

shiro安全框架异常退出没有清除缓存信息处理方案,最近项目遇到问题,shiro框架异常退出没有清除缓存信息,服务器重启后,又拿旧的缓存session来登录,造成后台报错。

这里转载网友的文章,记录一下解决方法。大体就是重写sessionManager类,做一个清除操作。

shiro安全框架异常退出

shiro安全框架异常退出

配置默认会话管理器:

<bean id="sessionManager" class="com.xzjc.common.security.SimpleWebSessionManager">
	<property name="globalSessionTimeout" value="15000" />
	<property name="sessionValidationInterval" value="30000" />
	<property name="sessionValidationSchedulerEnabled" value="true" />
</bean>

全局的会话信息设置成15秒,检测扫描信息间隔30秒,第三个参数就是是否开启扫描

重写管理器类的一个方法

package com.xzjc.common.security;

import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;


/**
 * 会话管理器,重写
 * @author zhouyujie
 */
public class SimpleWebSessionManager extends DefaultWebSessionManager {

	private CacheManager cacheManager;

	private final static Logger logger = Logger.getLogger(SimpleWebSessionManager.class);

	public SimpleWebSessionManager() {
		super();
	}

	public void validateSessions() {
		if (logger.isInfoEnabled()){
			logger.info("Validating all active sessions...");
		}
		int invalidCount = 0;
		Collection<?> activeSessions = getActiveSessions();
		if (activeSessions != null && !activeSessions.isEmpty()) {
			for (Iterator<?> i$ = activeSessions.iterator(); i$.hasNext();) {
				Session session = (Session) i$.next();
				try {
					SessionKey key = new DefaultSessionKey(session.getId());
					validate(session, key);
				} catch (InvalidSessionException e) {
					if (cacheManager != null) {
						SimpleSession s = (SimpleSession) session;
						if (s.getAttribute("portal.session.id") != null){
							cacheManager.getCache(null).remove(s.getAttribute("portal.session.id"));
						}
					}
					if (logger.isDebugEnabled()) {
						boolean expired = e instanceof ExpiredSessionException;
						String msg = (new StringBuilder()).append("Invalidated session with id [").append(session.getId()).append("]").append(expired ? " (expired)" : " (stopped)").toString();
						logger.debug(msg);
					}
					invalidCount++;
				}
			}

		}
		if (logger.isInfoEnabled()) {
			String msg = "Finished session validation.";
			if (invalidCount > 0){
				msg = (new StringBuilder()).append(msg).append("[").append(invalidCount).append("] sessions were stopped.").toString();
			}else{
				msg = (new StringBuilder()).append(msg).append("No sessions were stopped.").toString();
			}
			logger.info(msg);
		}
	}

	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

}

这样就好使了。

退出移动版