对会话标识未更新的处理

解决一个会话标识未更新的安全问题,网上的办法不尽能完全解决,最后这样搞了,记录一下。

             对会话标识未更新的处理_第1张图片

网上看到的解法,首页加了段:

//废弃登陆前的会话
if(request.getSession(false) != null){ 
request.getSession(false).invalidate();
}
Cookie[] cookies = request.getCookies();
if(cookies != null){
// out.println(cookies[0].getName() + "===>" + cookies[0].getValue());
cookies[0].setMaxAge(0);
response.addCookie(cookies[0]);

但是不是所有的都搞定了,于是搞了个过滤器,这个过滤器的原理是:让原来的会话过期,拿到新生成的会话,获取其sessionid,付给会话标识cookie,有时候可能要用原会话里的属性,于是又把原会话里的属性复制到新会话里。


public class SessionIDChangeFilter implements Filter {


    /**
     * Default constructor. 
     */
    public SessionInvalidateFilter() {
        
    }


public void destroy() {

}


/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
//中转用的map
Map attributeMap = new HashMap();

HttpSession oldSession = httpRequest.getSession(false);
if(oldSession != null){
//复制老会话里的属性到中转map
Enumeration attributeNames = oldSession.getAttributeNames();
String tem = null;
while(attributeNames.hasMoreElements()){
tem = attributeNames.nextElement();
attributeMap.put(tem, oldSession.getAttribute(tem));
}
//废弃老的会话
oldSession.invalidate();
}

HttpSession newSession = httpRequest.getSession(true);
Cookie[] cookies = httpRequest.getCookies();

//map里值copy到新session里
for(String key : attributeMap.keySet()){
newSession.setAttribute(key, attributeMap.get(key));


}
//新session的标识发给标识cookie
if(cookies != null){
for(Cookie c : cookies){
if(c.getName().equals("JSESSIONID")){
System.out.println(c.getValue());
c.setValue(newSession.getId());
httpResponse.addCookie(c);
System.out.println(c.getValue());
}
}
}


chain.doFilter(httpRequest, httpResponse);
}


public void init(FilterConfig fConfig) throws ServletException {

}
}

你可能感兴趣的:(技术实现点,安全,sessioncookie)