Issue
I'm passing some information at login inside a cookie, information which I need to remove at logout. For passing & deleting the cookie, I'm using HttpServletResponse. The cookie is visible in the client, but not deleted.
Adding the cookie:
Cookie cookie = new Cookie(name, value);
cookie.setHttpOnly(true);
cookie.setSecure(false);
cookie.setMaxAge(age);
cookie.setPath("/");
cookie.setDomain("localhost");
response.addCookie(cookie);
Remove:
Cookie cookie = new Cookie(name, null);
cookie.setHttpOnly(true);
cookie.setSecure(false);
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain("localhost");
response.addCookie(cookie);
The name passed is the same, I'm using a constant variable for both, so this is not the issue. I read a lot of questions, but all of them were solved with setMaxAge to 0, which in my case is set correctly. I don't know what to do.
Solution
So I found a solution and I want to post it here to help other developers in need.
The problem was not with my backend, the cookie was set correct and also deleted as specified in documentation. But the fact was that the cookie was set from an endpoint that does not require authentication and I was trying to delete it from an endpoint which requires authentication.
As you can deduce, the problem was with my front-end and cors requests. I had to add an interceptor where for every request I added {withCredentials: true}, which enabled to send & accept cookies from the server.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true
});
return next.handle(req);
}
Thanks!
Answered By - Ciprian Teletin