其他分享
首页 > 其他分享> > spring security登录前后sessionId不一致

spring security登录前后sessionId不一致

作者:互联网

spring security为了防止固定回话攻击会一直修改sessionId,所以在登录前存在session里的数据在登录后是获取不到的。为了解决这种情况可以监听session的变化做相应的更改。

@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionIdListener {


    @Override
    public void sessionCreated(HttpSessionEvent se) {
        StaticSessionContext.addSession(se.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        StaticSessionContext.removeSession(session);
    }


  	// 在改方法中可以将原来session的数据移到新的session中
    @Override
    public void sessionIdChanged(HttpSessionEvent httpSessionEvent, String oldSessionId) {
        HttpSession oldSession = StaticSessionContext.getSession(oldSessionId);
        if(oldSession != null) {
            StaticSessionContext.removeSession(oldSession);
        }
        StaticSessionContext.addSession(httpSessionEvent.getSession());
    }
}
public class StaticSessionContext {

    private static ConcurrentMap<String, HttpSession> attributes = new ConcurrentHashMap();

    private StaticSessionContext() {

    }

    public static void addSession(HttpSession session) {
        if(session != null) {
            System.err.println(session.getId());
            attributes.put(session.getId(), session);
        }
    }

    public static void removeSession(HttpSession session) {
        if(session != null) {
            attributes.remove(session.getId());
        }
    }

    public static HttpSession getSession(String sessionId) {
        if(sessionId == null) {
            return null;
        }
        return attributes.get(sessionId);
    }


}

参考地址:https://blog.csdn.net/qq_36500178/article/details/113091776

标签:getSession,StaticSessionContext,spring,void,sessionId,session,security,null,publ
来源: https://www.cnblogs.com/yourblog/p/16110538.html