在 Spring Security 3.0 中登录时设置 cookie

Posted

技术标签:

【中文标题】在 Spring Security 3.0 中登录时设置 cookie【英文标题】:Setting a cookie upon login in Spring Security 3.0 【发布时间】:2011-05-17 10:46:04 【问题描述】:

当有人登录时我需要设置一个 cookie,并且出现的 JSP 页面需要能够在 javascript 中读取该 cookie 并基于它执行操作。我坚持的部分是在登录时设置一个 cookie。我正在使用 Spring 3.0 和 Spring Security 3.0。

我已经注册了一个 LoginListener:

public class LoginListener implements ApplicationListener 
    public void onApplicationEvent(ApplicationEvent event) 
        if (event instanceof AuthenticationSuccessEvent) 
            somehowGetResponseObject.addCookie(new Cookie(name, value));
        
    

理想情况下,我还可以获取请求对象,以便找到 contextPath 并将其设置为 cookie 路径。我可以将 cookie 添加到 ThreadLocal 对象,然后稍后在我确实可以访问响应对象时读取它,但是以后是否可以访问该对象?我不太热衷于将 cookie 添加到 Session 中,然后在生成的 JSP 页面中读取它,但如果必须,我会这样做。我可以访问 HttpSession 吗?

更新:指定 authentication-success-handler-ref 解决了这个问题:http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html#form-login-flow-handling

【问题讨论】:

【参考方案1】:

完全不同的东西,你为什么不直接打印那个值,就好像它是一个 JS 变量一样?

<script>
    var something = '$somebean.someproperty';
    if (something) 
        performActionWith(something);
    
</script>

【讨论】:

当有人登录时,我需要在 javascript 中执行一个操作。但是那个人可以登录并最终访问任何网页,所以我事先不知道他们将要访问的页面登陆。 这正是我在示例中添加if 条件的原因。如果用户已登录,则设置 bean 属性,如果没有,则设为 null。 我如何知道用户刚刚登录?如果用户刚刚在此会话中首次登录,我只想执行 javascript 操作。 您在问题中使用了if (event instanceof AuthenticationSuccessEvent)。我不做 Spring,但如果这有效,那么它是完全可行的。您只需设置一些 Spring bean 属性,然后将其打印为 JS 变量。

以上是关于在 Spring Security 3.0 中登录时设置 cookie的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security 3.0:认证后的 GET 请求

Grails 3.0 中的 Spring Boot Security login.html 位置

Grails 3.0 和 Spring Security

如何在自定义 Spring security 3.0 身份验证中正确处理异常?

在 Grails 3.0 中配置 Spring Boot Security 以使用 BCrypt 密码编码

带有 jdbc 的 Spring Security 3.0