• 【Cookie】后端在Response中Set-Cookie无效


    【问题现象】

    在前端访问后端接口,后端通过Response来设置Cookie时(代码如下),并没有产生效果:

    public static Cookie buildCookie(String name, String value, int maxAge, String domain) {
    		Cookie cookie = new Cookie(name, value);
    		cookie.setSecure(true);
    		cookie.setHttpOnly(true);
    		cookie.setPath("/");
    		if (maxAge != 0) {
    			cookie.setMaxAge(maxAge);
    		}
    		if (domain != null && !"".equalsIgnoreCase(domain)) {
    			cookie.setDomain(domain);
    		}
    		return cookie;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    ![在这里插入图片描述](https://img-blog.csdnimg.cn/4985bce9843249f6bee3abdd5b783e1b.png
    在这里插入图片描述
    在前端浏览器开发者模式中,观察接口(该后端接口负责种Cookie)请求结果如下,Response中Set-Cookie内容正确,但出现异常标记,如图:在这里插入图片描述
    同时查看Cookie页,也为异常黄色,同时有相应secure提示,如图:
    在这里插入图片描述

    【原因】

    原因非常简单,我们会发现这种情况只会在http请求中发生,是因为后端在种cookie时,设置了secure为true。
    若secure为true,表示创建的cookie只能在HTTPS连接中被浏览器传递到服务器端,进行会话验证,如果是HTTP连接则不会传递该信息,所以安全性更高,不会被窃听。具体如下:

    如果HTTP连接在setSecure(true) 的情况下,只有服务器端的cookie会传递到浏览器端,浏览器端的cookie不会传递到服务器端;同时浏览器端收到服务器端的cookie,也不会自动写入。

    【解决】

    解决比较容易,后端种cookie时,不要设置secure为true;另外,如果只有http连接,同时浏览器端也需要使用cookie中内容,则需要把httpOnly改为false,否则浏览器端会被限制获取和使用cookie。
    如下:

    	public static Cookie buildCookie(String name, String value, int maxAge, String domain) {
    		Cookie cookie = new Cookie(name, value);
    //		cookie.setSecure(true);
    		//如果只有http连接,同时浏览器端也需要使用cookie中内容,则需要把httpOnly改为false,否则浏览器端会被限制获取和使用cookie
    //		cookie.setHttpOnly(true);
    		cookie.setPath("/");
    		if (maxAge != 0) {
    			cookie.setMaxAge(maxAge);
    		}
    		if (domain != null && !"".equalsIgnoreCase(domain)) {
    			cookie.setDomain(domain);
    		}
    		return cookie;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    重新启动,调用种cookie接口后,一切正常:
    在这里插入图片描述
    在这里插入图片描述
    同时也能在cookie管理器中看到该cookie:
    在这里插入图片描述

  • 相关阅读:
    Netty+SpringBoot 打造一个 TCP 长连接通讯方案
    Gitee Pages个人简历部署(上)
    C++初阶(运算符重载汇总+实例)
    自定义MVC(导成jar包)+与三层架构的区别+反射+面试题
    数据库修改和忘记密码的解决方法(附详细步骤和操作图)
    东南亚电商市场不欢迎独立站
    SQL语句中对时间字段进行区间查询
    21.2 Python 使用Scapy实现端口探测
    React查询、搜索类功能的实现
    SpringBoot整合Swagger3,赶紧整起来!
  • 原文地址:https://blog.csdn.net/ooppookid/article/details/126750659