Issue
Currently setting up http only cookie in a Spring boot project via configurations as follows.
This cookie is getting set correctly when ever I call following endpoint.
@Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setDomainNamePattern(".*");
serializer.setCookieName("my_cookie");
serializer.setCookieMaxAge(60 * 10); // 10 mins
serializer.setUseSecureCookie(true);
serializer.setUseHttpOnlyCookie(true);
return serializer;
}
As can see, the cookie called my_cookie
is being set for 10 mins.
In my controller within same project, I have the following controller method.
In the event I enter the error block, I wish to delete the cookie called my_cookie
. How can I do that?
This is the closest question I found for this but is not the same case considering I set it via configurations.
https://stackoverflow.com/questions/9821919/delete-cookie-from-a-servlet-response
@PostMapping(value = "/endpoint")
public List CustomResponse(
@RequestBody Request request,
// this is a session cookie coming from frontend, not related to the cookie I want to delete
@CookieValue(required = false) String otherCookie
) throws Exception {
CustomResponse response = null;
if (otherCookie != null) {
CustomResponse response = // perform some other rest request and get value from there
}
if (response == null) {
// I want to delete the cookie named `my_cookie` at this stage.
throw new CustomException('name');
}
return response;
}
Solution
To delete a cookie, set the Max-Age directive to 0 and unset its value. You must also pass the same other cookie properties you used to set it. Don't set the Max-Age directive value to -1. Otherwise, it will be treated as a session cookie by the browser.
// create a cookie
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/");
//add cookie to response
response.addCookie(cookie);
For more, refer to the post by Dzone: https://dzone.com/articles/how-to-use-cookies-in-spring-boot
Answered By - Pranay Srivastava