Shiro整合Redis共享Session后出现There is no session with id的问题
Shiro整合Redis共享Session后出现There is no session with id的问题
一、问题描述
org.apache.shiro.session.UnknownSessionException: There is no session with id [6ec13a08-5ea9-488a-bbb3-0c9da209fb31]
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:148) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:152) ~[shiro-core-1.4.0.jar:1.4.0]
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.setAttribute(AbstractNativeSessionManager.java:256) ~[shiro-core-1.4.0.jar:1.4.0]
at org
二、原因&解决办法
只所以出现这个问题是因为在shiro的DefaultWebSessionManager类中,默认Cookie名称是JSESSIONID,这样的话与servlet容器名冲突, 如jetty, tomcat等默认JSESSIONID, 当跳出shiro servlet时如error-page容器会为JSESSIONID重新分配值导致登录会话丢失!
修改ShiroConfig.java给sessionManager设置一个cookie的名字,名称随意只要不叫JSESSIONID就行。
@Bean
public SimpleCookie cookie() {
// cookie的name,对应的默认是 JSESSIONID
SimpleCookie cookie = new SimpleCookie("SHAREJSESSIONID");
cookie.setHttpOnly(true);
// path为 / 用于多个系统共享JSESSIONID
cookie.setPath("/");
return cookie;
}
@Bean
public SecurityManager securityManager(AuthorizingRealm myShiroRealm, RedisSessionDAO redisSessionDAO, RedisCacheManager redisCacheManager) {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// 设置session超时
sessionManager.setGlobalSessionTimeout(session_expire);
// 删除无效session
sessionManager.setDeleteInvalidSessions(true);
// 设置JSESSIONID
sessionManager.setSessionIdCookie(cookie());
// 设置sessionDAO
sessionManager.setSessionDAO(redisSessionDAO);
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setSessionManager(sessionManager);
securityManager.setCacheManager(redisCacheManager);
securityManager.setRememberMeManager(cookieRememberMeManager());
securityManager.setRealm(myShiroRealm);
return securityManager;
}
-------------已经触及底线 感谢您的阅读-------------