2011-05-18 47 views
3

我的應用程序使用java servlets,jsp和tomcat 6.我喜歡實現會話ID更改並希望在登錄後將舊會話屬性複製到新會話。我們在這裏開始使用一點點的彈簧。 這是將此功能添加到10年前的應用程序中的最佳方式。會話ID更改和登錄後的屬性複製

+0

爲什麼你需要更改會話ID? – 2011-05-18 11:15:55

+2

@ChristofferHammarström:登錄後查找會話id可防止會話劫持。 – Ralph 2011-05-18 11:20:24

回答

9

如果您使用Spring Security,框架默認會在登錄後更改會話ID。

@see Spring Security FAQ

爲什麼會話ID的變化,當我通過Spring Security的認證?

使用默認配置,當用戶驗證並創建一個新會話並將會話數據傳送給它時,Spring Security使現有會話無效。目的是改變會話標識符以防止「會話固定」攻擊。你可以找到更多關於這個在網上和參考手冊


如果你不使用Spring(安全),你必須自己做。在這樣的位:

public class Login extends HttpServlet { 
... 
    HttpSession session = request.getSession(); 
    Map<String,Object> values = session.GetAll(); //This line is psydo code 
    //Use getValueNames() and a loop with getValue(String name); 

    // Kill the current session 
    session.invalidate(); 

    HttpSession newSession = request.getSession(true); 
    newSession.putAllValues(values); //This line is psydo code 
... 
+0

當我調用session.invalidate()拋出一個exception.java.lang.IllegalStateException:getLastAccessedTime:會話已經失效 – coder247 2011-05-19 07:21:18

+0

據我瞭解:該文件說你不需要做任何事情。在嘗試實現自己的邏輯之前,你是否檢查過會話ID不會自動更改? – Ralph 2011-05-19 07:28:14

+0

對不起。背景是不同的。這不是關於彈簧安全 – coder247 2011-05-19 07:33:18

0

這可能有助於

Cookie cookie = new Cookie("JSESSIONID", null); 
cookie.setPath("/"); 
cookie.setMaxAge(0); 
response.addProperty(cookie); 
1
session=request.getSession(true); 
    Enumeration keys = session.getAttributeNames();  
    HashMap<String,Object> hm=new HashMap<String,Object>(); 
    while (keys.hasMoreElements()) 
    { 
     String key = (String)keys.nextElement(); 
     hm.put(key,session.getValue(key)); 
     session.removeAttribute(key);  
    } 
    session.invalidate(); 
    session=request.getSession(true); 
    for(Map.Entry m:hm.entrySet()) 
    { 
     session.setAttribute((String)m.getKey(),m.getValue()); 
     hm.remove(m); 
    } 
+1

一些更多的解釋可以幫助人們清楚地理解 – Prasad 2016-12-31 06:46:19