Reputation: 129
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
But it won't add it to the storage
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?
Upvotes: 4
Views: 19962
Reputation: 41
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.
Upvotes: 4
Reputation: 99
Cookies are accessibles only if the JS is provided from the same origin (host:port).
You may use URL rewriting approach to use the same origin for your assets and API. You may look at devServer if your are using Webpack.
Consider LocalStorage that offer more modern approach to deal with it as well.
Regards.
Upvotes: 3
Reputation: 129
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");
Upvotes: 4