java – 在Spring Security登录期间添加cookie

我有一个使用Spring Security的Web项目,我试图在处理身份验证成功的方法中保存cookie.但是,当我查看浏览器的cookie时,只显示JSESSIONID,当我在Spring重定向到的servlet上查看request.getCookies()时,会发生相同的情况.

我试图将cookie保存在应用程序的一个servlet中,并且cookie保存正确,因此Spring Security可能会清除响应.你有什么主意吗?

一种解决方法是将其保存在Session中,然后获取它并将cookie保存在登录重定向到的servlet上.另一个是使用像this这样的javascript保存cookie.但我不喜欢这些解决方案.提前致谢

这是相关代码

public class RoleBasedAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements
    AuthenticationSuccessHandler {
    ...
    // save a cookie with the selected language
    MaparameterMap = request.getParameterMap();
    if (parameterMap.containsKey("language")) {
        saveCookie("language",parameterMap.get("language")[0],response);
    }
}

public static void saveCookie(String cookieName,String value,HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName,value);
    //maxAge is one month: 30*24*60*60 
    cookie.setMaxAge(2592000);
    cookie.setDomain("projectName");
    cookie.setPath("/");
    response.addCookie(cookie);
    }
}

ecurity:http auto-config="false" ...>
    ecurity:form-login login-page="/login.do" authentication-success-handler-ref="redirectRoleStrategy" .../>
    ...
ecurity:http>

ecurity.RoleBasedAuthenticationSuccessHandler">
    
最佳答案
您是否在RoleBasedAuthenticationSuccessHandler中调用super之前或之后设置cookie?

 super.onAuthenticationSuccess(request,response,authentication);

您必须在调用super之前设置cookie,因为超类中的逻辑将发送重定向,因此阻止您更新HttpServletResponse的内容.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...