Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JWT Token in the body of response Java Spring

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

like image 387
Hamza Avatar asked Aug 24 '18 07:08

Hamza


People also ask

Should I send JWT token in header or body?

In most cases, however, it is passed in HTTP headers. You need to carefully analyse your scenario and determine the best way to implement JWT's in your project. Yes you have to. if you send token through body or as a query then the attacker will see through your URL and go inside your database.


1 Answers

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

like image 156
Mr. Skip Avatar answered Nov 14 '22 21:11

Mr. Skip