java 登录后会话 ID 更改和属性复制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6042846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
session id change and attributes copying after login
提问by coder247
My application use java servlets,jsp and tomcat 6. I like to implement session id change and want to copy the old session attributes to the new one after login. We started using a little bit of spring in this. Which is the best way to add this feature to a 10 year old application like this.
我的应用程序使用 java servlets、jsp 和 tomcat 6。我喜欢实现会话 ID 更改,并希望在登录后将旧会话属性复制到新会话属性。我们开始在这方面使用一点弹簧。这是将此功能添加到像这样的 10 年历史的应用程序的最佳方式。
回答by Ralph
If you use Spring Security, the framework should change the session id after login by default.
如果你使用 Spring Security,默认情况下框架应该在登录后更改 session id。
@see Spring Security FAQ:
@see Spring 安全常见问题解答:
Why does the session Id change when I authenticate through Spring Security?
With the default configuration, Spring Security invalidates the existing session when the user authenticates and creates a new one, transferring the session data to it. The intention is to change the session identifier to prevent “session-fixation” attacks. You can find more about this online and in the reference manual
为什么当我通过 Spring Security 进行身份验证时会话 ID 会发生变化?
使用默认配置,当用户进行身份验证并创建新会话时,Spring Security 使现有会话无效,并将会话数据传输给它。目的是更改会话标识符以防止“会话固定”攻击。您可以在网上和参考手册中找到更多相关信息
If you do not use Spring (Security) you have to do it by your own. A bit in this way:
如果您不使用 Spring (Security),则必须自己完成。有点像这样:
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
...
回答by sachin berad
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);
}
回答by Ankit
This might help
这可能有帮助
Cookie cookie = new Cookie("JSESSIONID", null);
cookie.setPath("/");
cookie.setMaxAge(0);
response.addProperty(cookie);