【问题标题】:How to delete a cookie from backend upon an error发生错误时如何从后端删除 cookie
【发布时间】:2021-11-11 19:56:21
【问题描述】:

目前在 Spring Boot 项目中通过如下配置设置 http only cookie。
当我调用以下端点时,此 cookie 设置正确。

  @Bean
  public CookieSerializer defaultCookieSerializer() {
    DefaultCookieSerializer cookie = new DefaultCookieSerializer();
    cookie.setDomainNamePattern(".*");
    cookie.setCookieName("my_cookie");
    cookie.setUseSecureCookie(true);
    cookie.setUseHttpOnlyCookie(true);
    cookie.setCookieMaxAge(1200);
    return cookie;
  }

可以看到,名为my_cookie 的cookie 被设置了2 分钟。
在同一项目中的控制器中,我有以下控制器方法。
如果我输入错误块,我希望删除名为my_cookie 的cookie。我该怎么做?

这是我为此找到的最接近的问题,但考虑到我通过配置设置它,情况并不相同。
https://stackoverflow.com/questions/9821919/delete-cookie-from-a-servlet-response

  @PostMapping(value = "/endpoint")
  public List CustomResponse(
          @RequestBody Request request,
  ) 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;
  }

【问题讨论】:

标签: java spring spring-boot spring-mvc cookies


【解决方案1】:

要删除 cookie,请将 Max-Age 指令设置为 0 并取消设置它的值。您还必须传递用于设置它的相同其他 cookie 属性。不要将 Max-Age 指令值设置为 -1。否则,浏览器会将其视为会话cookie。

// 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);

更多内容请参考 Dzone 的帖子: https://dzone.com/articles/how-to-use-cookies-in-spring-boot

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 2021-09-20
    • 2023-03-14
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2013-06-07
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多