security - 带有 session Cookie 的 Spring Security RememberMe 服务

标签 security spring authentication spring-security remember-me

我正在使用 Spring Security 的 RememberMe 服务来保持用户的身份验证。

我想找到一种简单的方法来将 RememberMe cookie 设置为 session cookie 而不是具有固定的到期时间。对于我的应用程序,cookie 应该一直存在,直到用户关闭浏览器。

关于如何最好地实现这一点的任何建议?是否担心这是一个潜在的安全问题?

这样做的主要原因是,使用基于 cookie 的 token ,负载均衡器后面的任何服务器都可以为 protected 请求提供服务,而无需依赖存储在 HttpSession 中的用户身份验证。事实上,我已经明确告诉 Spring Security 永远不要使用命名空间创建 session 。此外,我们使用的是 Amazon 的 Elastic Load Balancing,因此不支持粘性 session 。

注意:虽然我知道截至 4 月 8 日,亚马逊现在支持粘性 session ,但由于其他一些原因,我仍然不想使用它们。也就是说,一台服务器的过早消亡仍会导致与其关联的所有用户的 session 丢失。
http://aws.amazon.com/about-aws/whats-new/2010/04/08/support-for-session-stickiness-in-elastic-load-balancing/

最佳答案

Spring Security 3 不提供如何生成 cookie 的配置。您必须覆盖默认行为:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;

/** Cookie expires on session. */
 public class PersistentTokenBasedRememberMeServicesCustom extends
   PersistentTokenBasedRememberMeServices {

  /** only needed because super throws exception. */
  public PersistentTokenBasedRememberMeServicesCustom() throws Exception {
    super();
  }

  /** Copy of code of inherited class + setting cookieExpiration, */
  @Override
  protected void setCookie(String[] tokens, int maxAge,
      HttpServletRequest request, HttpServletResponse response) {
    String cookieValue = encodeCookie(tokens);
    Cookie cookie = new Cookie(getCookieName(), cookieValue);
    //cookie.setMaxAge(maxAge); 
    cookie.setPath("/");
    cookie.setSecure(false); // no getter available in super, so always false

    response.addCookie(cookie);
  }
}

确保你使用这个定制的 PersistentTokenBasedRememberMeServices for you're rememberMeService 通过将类名添加到它的 bean 配置中:
<beans:bean id="rememberMeServices"
 class="my.custom.spring.PersistentTokenBasedRememberMeServicesCustom"/>

关于security - 带有 session Cookie 的 Spring Security RememberMe 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2608372/

相关文章:

amazon-web-services - 如何为 Amazon EMR 生成 trustedCertificates.pem 和 certificateChain.pem 文件?

python - 是否可以针对 ODBC 驱动程序连接使用 SQLMAP?

php - laravel 5 中的两种登录表单

node.js - 用于提供静态文件的快速基本身份验证

java - Spring Security LDAP 和记住我

ruby-on-rails-3 - 轨道与设计 : How to authenticate specific user?

javascript - jQuery(userInput) "safe"适合最终用户吗?

ruby-on-rails - 我可以加密我的应用程序和数据库之间传输的数据吗

java - 可以在 Scala 中使用 Spring 缓存

Java、Spring、Ant部署两个war文件