8

I send the token of JWT in Header, but the client need it in the body of the response, how can I put it in the response :

    @Override
    protected void successfulAuthentication(
            HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {

    User springUser = (User) authResult.getPrincipal();
    String jwt = Jwts.builder()
            .setSubject(springUser.getUsername())
            .setExpiration(new Date(System.currentTimeMillis()+SecurityConstants.EXPIRATION_TIME))
            .signWith(SignatureAlgorithm.HS256, SecurityConstants.SECRET)
            .claim("roles",springUser.getAuthorities())
            .compact();
    response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX+jwt);
    }

I need to put the token in the response

Hamza
  • 93
  • 1
  • 2
  • 8

1 Answers1

18

If I understand you properly you just need to create a response body

response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(
            "{\"" + SecurityConstants.HEADER_STRING + "\":\"" + SecurityConstants.TOKEN_PREFIX+jwt + "\"}"
    );

Take a look at How do you return a JSON object from a Java Servlet

Mr. Skip
  • 417
  • 4
  • 10
  • This response have opened my eyes... after a long researching with no success, finally I've got this solution and it worked fine for me. I needed to return the token in my response body and this is what I did (following this solution). Thank you very much – Camilo Silva Dec 07 '20 at 14:50
  • 1
    Hello, I'm doing the same thing in my web application. I just want to know is it safe to share tokens on response body ? – anasse hanafi Dec 11 '20 at 20:30