Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 332
Blogger 2015 Avatar asked Sep 06 '25 03:09

Blogger 2015


1 Answers

Chrome has changed its recent policies not to support localhost or development cookies, so you have to work around and play it with HTTP cookie

 ResponseCookie resCookie = ResponseCookie.from(cookieName, cookieValue)
            .httpOnly(true)
            .sameSite("None")
            .secure(true)
            .path("/")
            .maxAge(Math.toIntExact(timeOfExpire))
            .build();
    response.addHeader("Set-Cookie", resCookie.toString());

This thing works for me but, make sure it only works for https (not HTTP) and this thing is a makeover for development purposes only, once if you host your server chrome allows response cookies else it just blocks all kinds of HTTP cookies.

like image 114
Pranay K Avatar answered Sep 07 '25 21:09

Pranay K