Cookie not set in chrome even when React app is served from the same port as Spring Boot

Viewed 747

I have an application running on http://localhost:8181/ which has React integrated with Spring Boot. (both run on the same port). I send this POST request to http://localhost:8181/public/authenticate using axios:

The axios instance:

export const axios_register_login_user = axios.create({
baseURL: '/public',
withCredentials: true,
headers: { "content-type": "application/json" },
method: 'POST'

})

The login request:

export async function login(username, password, callback) {

    axios_register_login_user.post("/authenticate", {
        'username': username,
        'password': password
    }).then(response => {
        console.log("success", response);
        callback(response.data);

    }).catch(error => {
        console.log("failed", error);
        callback("Failed");
    })
}

The login is successful and I can see a cookie being returned in the response enter image description here

However, this cookie is not set in the Application->Cookies tab enter image description here

Here's my API code:

    @RequestMapping(value = "/authenticate", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
  public ResponseEntity<?> authenticateUser(@RequestBody AuthenticationRequest request, HttpServletResponse response) {
    try {
      UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
      authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    } catch (BadCredentialsException e) {
      throw new BadCredentialsException("Invalid details");
    }
    UserDetailsImpl userDetails = (UserDetailsImpl) userDetailsService.loadUserByUsername(request.getUsername());
    String name = userDetails.getUser().getName();
    String generatedToken = jwtUtil.generateToken(userDetails);
    Cookie cookie = new Cookie("jwt", generatedToken);
    cookie.setMaxAge(60 * 60 * 10);//like JWT, the max age is 10 hours
    // cookie.setSecure(false);
    cookie.setHttpOnly(true);
    response.addCookie(cookie);
    return new ResponseEntity<>(new AuthenticationResponse(name + " " + generatedToken), HttpStatus.OK);
  }

I tried adding

  @CrossOrigin(allowCredentials = "true", origins = "{http://localhost:3000,http://localhost:8181}") 

to the above method but it didn't help.

Please help me out with this. I've been stuck here for 2 days now :(

1 Answers

I was missing cookie.setPath("/") in my code.

Additionally, I also did cookie.setSecure(false);

After these changes, the cookie was added to the browser

enter image description here

Related