【发布时间】:2019-08-13 02:28:23
【问题描述】:
我使用不同的用户帐户登录,但我有带有已创建的 http 会话 ID 的 hashmap,我需要使用 sessionid 使 http 会话无效。
有没有办法做到这一点?
【问题讨论】:
-
创建一个关闭其会话的 servlet,然后使用会话 ID 执行 http 请求。
标签: java http session tomcat servlets
我使用不同的用户帐户登录,但我有带有已创建的 http 会话 ID 的 hashmap,我需要使用 sessionid 使 http 会话无效。
有没有办法做到这一点?
【问题讨论】:
标签: java http session tomcat servlets
没有标准的方法来删除只知道会话 id 的会话。
也许您可以通过发送虚假会话 id(作为 cookie 或 http 参数)来欺骗服务器以接管其他人的会话并尝试使用某些应用程序的方法(例如“注销”)使其无效。
但是tomcat中没有JSP之类的东西可以做到这一点。
如果您想使部署在该服务器上的应用程序中的会话无效,您可能对How can i load Java HttpSession from JSESSIONID? 感兴趣
【讨论】:
对此有几个解决方案。 解决方案1: 在这里描述 How can i load Java HttpSession from JSESSIONID? 这里的问题是我们需要存储在 Map 中创建的所有会话。这里存在安全风险。
解决方案 2: 实现注销 API 像这样的东西。
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ResponseEntity<Resource> logout(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
LOG.info("Clean session: sessionId: [{}]", session == null ? "null" : session.getId());
if (session != null) {
session.invalidate();
}
return new ResponseEntity<>(new Resource<String>(), HttpStatus.OK);
}
调用此 API 时,在标头中添加以下 cookie,假设您的会话是 49A77C2ED71E3240FC2CC5DBD20C7CCE 那么请求将是这样的
curl --location --request PUT 'https://your.server.com/<somepath>/logout' \
--header 'Authorization: Some authToken if required' \
--header 'cookie: JSESSIONID=49A77C2ED71E3240FC2CC5DBD20C7CCE; Path=/<somepath>; Secure; HttpOnly'
【讨论】:
你可以在给定的方法下使用
session.invalidate();
或者您可以从会话中删除所有属性并使其无效
Enumeration<String> attributes = request.getSession().getAttributeNames();
while (attributes.hasMoreElements()) {
String attribute = attributes.nextElement();
session.removeAttribute(attribute);
}
session.invalidate();
【讨论】: