1

Does a post always use redirect to respond to a request. If so, how can I ensure that the response headers are also carried forward to the redirected url? Currently, I'm setting a JWT token in the response headers that I send but the redirected url doesn't contain the token. Can someone tell me how I can ensure that I get the JWT token so that I can use it in my further requests.

String token = JWT.create()
                .withSubject(((LdapUserDetails) authentication.getPrincipal()).getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(HMAC512(SECRET.getBytes()));
        response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);

        Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);

        if(redirectURLObject != null)
            setDefaultTargetUrl(redirectURLObject.toString());
        else{
            setDefaultTargetUrl("http://localhost:8000");
        }
request.getSession().removeAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
        super.onAuthenticationSuccess(request, response, authentication);

With JWT token before redirect

After Redirect- Without JWT

user3310115
  • 1,372
  • 2
  • 18
  • 48

1 Answers1

0

If you are sure about super.onAuthenticationSuccess(request, response, authentication); line, it is most likely the culprit.

I assume that your class is something like extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler {

If you dig deeper you'll find inside handle method in AbstractAuthenticationTargetUrlRequestHandler class which has this line:

redirectStrategy.sendRedirect(request, response, targetUrl); which will redirect within from your browser with 302 status.

If you understand this problem, it's not possible to have it in the header. There are other ways: you could make AJAX call from frontend, or returning JSON with JWT in header or having forwarding without sendRedirect.

May be you are looking to forward the request (RequestDispatcher.forward() vs HttpServletResponse.sendRedirect())

cosmos
  • 2,143
  • 2
  • 17
  • 27
  • I actually solved it by removing the redirect part. But the next request doesnt have the header. Should the front end set it manually by picking it from the response ? – user3310115 Sep 12 '18 at 05:21
  • Please update your question with full code and flow. I can't assume on what you did. – cosmos Sep 12 '18 at 13:24
  • I got the answer, acutually im going to another url. So i have to save it and insert the token in the header manually. – user3310115 Sep 12 '18 at 18:20