Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security - Get SESSION cookie value in AuthenticationSuccessHandler

I know that spring security creates a cookies names SESSION on successful authentication. Is it possible to get hold of that cookie value in AuthenticationSuccessHandler.

I have a following implementation inside which I need that SESSION cookie value. I looked as response headers of HttpServletResponse, but they have XSRF-TOKEN set-cookie headers,

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException {

   // GET SESSION, COOKIE VALUE HERE
  }
}

Can you please help.

like image 684
JavaCodeNet Avatar asked Jun 13 '26 12:06

JavaCodeNet


1 Answers

The SESSION cookie is created by Spring Session's DefaultCookieSerializer, which is called every time a new Session is created, and not necessarily after successful authentication.

Spring Session's SessionRepositoryFilter wraps the HttpServletRequest in such a way that whenever you obtain an HttpSession from the request at any point in your application, you're actually getting a Spring Session object. However, this cookie is written to the response after your handler has been called, as you can see in SessionRepositoryFilter:

try {
        filterChain.doFilter(wrappedRequest, wrappedResponse);
    }
    finally {
        wrappedRequest.commitSession(); //the SESSION cookie is created if necessary
    }

So if the session has just been created for this request...

  1. The cookie won't be available in the HttpServletRequest because the cookie hasn't been sent yet (and so the browser couldn't have sent it)
  2. The cookie won't be HttpServletResponse as a "Set-Cookie" header because it will be written after your application has handled the request.

However, you could get the cookie value:

String cookieValue = request.getSession().getId();

Note: The above code will force Spring Session to create a session backed Redis/Jdbc/etc that will be used later to generate the SESSION cookie.

like image 108
NatFar Avatar answered Jun 16 '26 07:06

NatFar