简体   繁体   中英

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!

Ok, I solved it.

It was a problem with CORS. You have to send all requests with the withCredentials flag set like that:

axios.defaults.withCredentials = true;

and allow the Credentials on the server side:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM