2


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!

Seb Aeneas
  • 23
  • 4
  • Does this answer your question? [Set a cookie to HttpOnly via Javascript](https://stackoverflow.com/questions/14691654/set-a-cookie-to-httponly-via-javascript) – dur Jan 26 '22 at 21:44
  • @dur No sadly not. I don't think my problem has anything to do with HttpOnly. I suspect it's rather a problem with CORS, but to be honest I don't really understand it. – Seb Aeneas Jan 27 '22 at 14:19
  • If you're hosting the UI separately, you are probably correct that it's a CORS issue. You won't be able to use a cookie. See the [JWT Login Sample](https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/java/jwt/login) to use built-in support for JWT authentication in Spring Security, with a custom endpoint. You will want to use the `Authorization` header instead of a cookie. – Steve Riesenberg Jan 27 '22 at 17:48
  • @SebAeneas Did you try `jwtCookie.setHttpOnly(false);` instead of `jwtCookie.setHttpOnly(true);`? ReactJs is a Javscript client and can't send `httpOnly` cookies. – dur Jan 27 '22 at 19:30

1 Answers1

0

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);
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
Seb Aeneas
  • 23
  • 4