Java httpservletrequest - 创建新会话/更改会话 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2311429/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:59:29  来源:igfitidea点击:

httpservletrequest - create new session / change session Id

javasessionservlets

提问by AJM

I'm maintaining a Java web application.

我正在维护一个 Java Web 应用程序。

Looking into the login code it gets an HttpSession out of HttpServletRequest via the getSession() method of HttpServletRequest. (It uses some values in the session for authentication purposes)

查看登录代码,它通过 HttpServletRequest 的 getSession() 方法从 HttpServletRequest 中获取 HttpSession。(它使用会话中的一些值进行身份验证)

However I'm worried about session fixation attacks so after I have used the initial session I want to either start a new session or change the session id. Is this possible?

但是,我担心会话固定攻击,因此在使用初始会话后,我想启动一个新会话或更改会话 ID。这可能吗?

采纳答案by pablochan

The Servlet 3.0 API doesn't allow you to change the session id on an existing session. Typically, to protect against session fixation, you'll want to just create a new one and invalidate the old one as well.

Servlet 3.0 API 不允许您更改现有会话的会话 ID。通常,为了防止会话固定,您只需要创建一个新的并使旧的无效。

You can invalidate a session like this

您可以像这样使会话无效

request.getSession(false).invalidate();

and then create a new session with

然后创建一个新会话

getSession(true)(getSession()should work too)

getSession(true)(也getSession()应该工作)

Obviously, if you have an data in the session that you want to persist, you'll need to copy it from the first session to the second session.

显然,如果会话中有要保留的数据,则需要将其从第一个会话复制到第二个会话。

Note, for session fixation protection, it's commonly considered okay to just do this on the authentication request. But a higher level of security involves a tossing the old session and making a new session for each and every request.

请注意,对于会话固定保护,通常认为对身份验证请求执行此操作是可以的。但是更高级别的安全性涉及为每个请求扔掉旧会话并创建一个新会话。

回答by Jakub Kubrynski

Since Java EE 7 and Servlet API 3.1 (Tomcat 8) you can use HttpServletRequest.changeSessionId()to achieve such behaviour. There is also a listener HttpSessionIdListenerwhich will be invoked after each change.

从 Java EE 7 和 Servlet API 3.1 (Tomcat 8) 开始,您可以使用HttpServletRequest.changeSessionId()来实现此类行为。还有一个侦听器HttpSessionIdListener,每次更改后都会调用它。