Add cookie during Spring Security Login

I have a web project with Spring Security, and I tried to save the cookie in a method that handles authentication success. However, when I look at browser cookies, only JSESSIONID appears, and the same thing happens when I look at request.getCookies () in the servlet that Spring redirects.

I tried to save the cookie in one of the servlets of the application and the cookie will be saved correctly, so maybe Spring Security will clear the response. Do you have any ideas?

One way would be to save it in the session, and then get it and save the cookie on the servlet to which the login is redirected. Another option is to save a cookie with javascript, for example. But I do not like these decisions. thanks in advance

Here is the relevant code:

public class RoleBasedAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements
    AuthenticationSuccessHandler {
    ...
    // save a cookie with the selected language
    Map<String, String[]> parameterMap = 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);
    }
}

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

<bean id="redirectRoleStrategy" class="com.companyName.security.RoleBasedAuthenticationSuccessHandler">
    <beans:property name="roleUrlMap">
        <beans:map>
            <beans:entry key="ROLE_ADMIN" value="/privat/application.do"/>
            ...
        </beans:map>
    </beans:property>
</bean>
+4
source share
2 answers

Do you set a cookie before or after calling super in the RoleBasedAuthenticationSuccessHandler?

 super.onAuthenticationSuccess(request, response, authentication);

You must set a cookie before your call is super, as the logic in the superclass will send a redirect and therefore will not allow you to update the contents of the HttpServletResponse.

+10
source

Try calling some kind of encoded value outside the if clause, just to make sure it works:

saveCookie("language", "en", response);

Also, as a test, try not to set the domain and cookie path initially:

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);

cookie , .

0

Source: https://habr.com/ru/post/1536850/


All Articles