Reputation: 37
I'm developing a web application using Angular for client-side and Java with Spring on server-side. I have read some articles, but haven't found concrete answers to my questions. The goal is store, read and modify cookies from both sides. I want to figure out handy and simple approach to store and read cookies.
First of all, are there some best practises/conventions to setting it on client-side, and then if it's needed read and modify on both sides or...?
I found that on client-side it's pretty easy using ngx-cookie-service. And with server-side it's worse. I have tried to add cookie in response in that way:
@RequestMapping("/")
public String hello(HttpServletResponse response) {
response.addCookie(new Cookie("foo", "bar"));
//..
}
But it doesn't store a cookie.
Also using Spring I have tried to read already stored cookie by client-side, but it also doesn't work:
@RequestMapping("/")
public String hello(@CookieValue("myCookie") String cookie){
log.info("My cookie {}", cookie);
(...)
}
Upvotes: 2
Views: 2169
Reputation: 321
check this: Access-Control-Allow-Credentials
Basically if your server has this setting in the header then your request to the server also has to have the withCredentials prop set to true
Upvotes: 2
Reputation: 57185
Client side its easy with various npm packages such as the one you mentioned.
Server side, you would typically use the "Set-Cookie" response header to set a cookie in the browser. This is typically done for authentication purposes on the /api/login endpoint response but you could use it for other purposes.
When using the Set-Cookie response header, it is good practice to make it HttpOnly which prevents JavaScript from accessing and tampering. It is simply sent in all subsequent API requests and JavaScript need not even worry about it.
This could be used, server-side, for example, when receiving an incoming request, to determine who the authenticated user is. And if not, give em a 401.
Secure means the cookie can only be passed over HTTPS protocol.
Docs: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
Not sure how you would code Java Spring to set the Set-Cookie response header, but I'm sure you can look that one up.
Edit: response_headers
Upvotes: 0