Search code examples
javascripthtmlspring-bootcookiessetcookie

Unable to set cookies with Spring Boot on the serve side


I'm using Spring Boot on server side. When I'm adding cookie to response it adds Set-cookie header with right value but when browser receives response it displays that header but won't set the cookie. Also Postman stores all cookies fine.

Spring

public ResponseEntity<?> authenticate(@RequestBody AuthenticationRequest request, HttpServletResponse response) throws Exception {
        Cookie cookie = new Cookie("token", "COOKIE_VALUE");
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        response.addCookie(cookie);
        return ResponseEntity.ok("Connection succeeded");
    }

JSfetch (from React app from different port)

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({"username":"TestUser","password":"pwd"});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://IP_ADDRESS:8080/authenticate", requestOptions)

Chrome's seeing cookie in the headers enter image description here

But it won't add it to the storage enter image description here

So does Firefox. What did I miss? Is there a solution to this? I'm using my internet ip address in fetch with port 8080 - not localhost. But localhost didn't do the trick either.

UPD. It seems working though when the ports are the same. I tried to return jsp page instead and that page executes the fech statement and it has stored the cookie. So solution to this is probably to compile react app and put it on the server. Anyway how to deal with cookies when the ports are not the same?


Solution

  • Ok, changing this in spring boot

    @CrossOrigin
    

    to this

    @CrossOrigin(origins = "http://MY_IP_ADDRESS", allowCredentials = "true")
    

    saved my day. I still don't get it why it didn't work when I set the headers manually as follows in the post mapping method

    response.addHeader("Access-Control-Allow-Credentials", "true");
    response.addHeader("Access-Control-Allow-Origin", "http://MY_IP_ADDRESS");