Search code examples
reactjscookiesspring-securityjwt

Browser doesn't store the JWT cookie even though Postman shows the cookie correctly



I try to build a web application with spring and react. In the authorization I send a JWT cookie like that:

final String jwt = jwtUtil.generateToken(user);
Cookie jwtCookie = new Cookie("jwt", jwt);
jwtCookie.setHttpOnly(true);
jwtCookie.setPath("/");
response.addCookie(jwtCookie);
return new ResponseEntity<String>(jwt, HttpStatus.OK);

And when I send the request in Postman the cookie is correctly shown: Postman screenshot

Now I want to authenticate myself with react like that:

return axios
        .post("http://localhost:8080/auth", {}, {
            auth: {
                username: uname,
                password: pass
            }

        })
        .then(response => {
            console.log(response)
            return response.data;
        });

But even though the authorization is successful and I can even store the jwt-token in the local storage, the cookie doesn't appear in the browser.

Does anyone have an idea how to fix that?
Thanks for your help!


Solution

  • It was a problem with CORS. You have to set the withCredentials flag to true in order for the cookie exchange to occur.

    axios.defaults.withCredentials = true;
    

    and allow the Credentials on the server side:

    registry
      .addMapping("/**")
      .allowedOrigins("http://localhost:3000")
      .allowCredentials(true);