I have a spring mvc backend at http://localhost:8080/
and a angular frontend at http://localhost:4200
. I am sending a cookie from backend to frontend but it isn't being saved by the browser.
I have configured cors in following way:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("http://127.0.0.1:4200");
}
And cors is working fine as I am able to do api request from frontend to backend.
I am sending a cookie in response:
Cookie code:
Cookie refreshCookie = new Cookie("x-refresh", "my-token");
refreshCookie.setPath("/");
refreshCookie.setMaxAge(2 * 60);
refreshCookie.setHttpOnly(true);
response.addCookie(refreshCookie);
Following header is sent in response:
Set-Cookie: x-refresh=my-token; Max-Age=120; Expires=Sun, 24 Sep 2023 06:27:26 GMT; Path=/; HttpOnly
My problem is the cookie isn't being saved in the browser storage and I also can't see it in devtools.
Why isn't cookie being saved in browser/
I got it solved. I thought I was sending Access-Control-Allow-Origin
header in my request but that wasn't the case.
After fixing my code and actually sending Access-Control-Allow-Origin
in the request, browser is saving the cookie and everything is working now.
Add Access-Control-Allow-Origin
in the request header: