Springboot应用中设置Cookie的SameSite属性

Easter79
• 阅读 1167

Cookie除了keyvalue以外有几个属性。

  • httpOnly 是否允许js读取cookie
  • secure 是否仅仅在https的链接下,才提交cookie
  • domain cookie提交的域
  • path cookie提交的path
  • maxAge cookie存活时间
  • sameSite 同站策略,枚举值:Strict Lax None

其他的都很熟悉了,最后一个是 Chrome 51 开始,浏览器的 Cookie 新增加了一个 SameSite 属性,用来防止 CSRF 攻击和用户追踪。

关于SameSite的详细解释 可以看 Cookie 的 SameSite 属性

在Javaweb应用中 ,设置 Cookie一般都是用 javax.servlet.http.Cookie,但是SameSite属性出来不久,Servlet库还没更新,所以没有设置SameSite的方法.

javax.servlet.http.Cookie 中定义的的属性

可以看到,还没有SameSite的定义

//
// The value of the cookie itself.
//

private String name; // NAME= ... "$Name" style is reserved
private String value; // value of NAME

//
// Attributes encoded in the header's cookie fields.
//

private String comment; // ;Comment=VALUE ... describes cookie's use
// ;Discard ... implied by maxAge < 0
private String domain; // ;Domain=VALUE ... domain that sees cookie
private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
private String path; // ;Path=VALUE ... URLs that see the cookie
private boolean secure; // ;Secure ... e.g. use SSL
private int version = 0; // ;Version=1 ... means RFC 2109++ style
private boolean isHttpOnly = false;

通过 ResponseCookie 给客户端设置Cookie

本质上,Cookie也只是一个header。我们可以不使用Cookie对象,而通过自定义Header的方式来给客户端设置Cookie

ResponseCookie 是Spring定义的一个Cookie构建工具类,极其简单

import java.time.Duration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class TestController {
    
    @GetMapping("/test")
    public Object test (HttpServletRequest request,
                    HttpServletResponse response) throws Exception {
        
        ResponseCookie cookie = ResponseCookie.from("myCookie", "myCookieValue") // key & value
                .httpOnly(true)        // 禁止js读取
                .secure(false)        // 在http下也传输
                .domain("localhost")// 域名
                .path("/")            // path
                .maxAge(Duration.ofHours(1))    // 1个小时候过期
                .sameSite("Lax")    // 大多数情况也是不发送第三方 Cookie,但是导航到目标网址的 Get 请求除外
                .build()
                ;
        
        // 设置Cookie Header
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        
        return "ok";
    }
}

响应给客户端的Cookie

Springboot应用中设置Cookie的SameSite属性

所有属性都响应正确 √

HttpSession依赖一个名称叫做JSESSIONID(默认名称)的Cookie。

对于JSESSIONID Cookie 的设置,可以修改如下配置。但是,目前spring也没实现SameSite的配置项。

配置类 : org.springframework.boot.web.servlet.server.Cookie

server.servlet.session.cookie.comment
server.servlet.session.cookie.domain
server.servlet.session.cookie.http-only
server.servlet.session.cookie.max-age
server.servlet.session.cookie.name
server.servlet.session.cookie.path
server.servlet.session.cookie.secure

通过修改容器的配置,对Session Cookie设置SameSite属性

Tomcat

import org.apache.tomcat.util.http.Rfc6265CookieProcessor;
import org.apache.tomcat.util.http.SameSiteCookies;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatConfiguration {

    @Bean
    public TomcatContextCustomizer sameSiteCookiesConfig() {
        return context -> {
            final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor();
            // 设置Cookie的SameSite
            cookieProcessor.setSameSiteCookies(SameSiteCookies.LAX.getValue());
            context.setCookieProcessor(cookieProcessor);
        };
    }
}

Spring Session的SameSite属性

通过自定义 CookieSerializer 设置 SameSite属性

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.web.http.CookieSerializer;

import com.video.common.spring.session.DynamicCookieMaxAgeCookieSerializer;

@Configuration
public class SpringSessionConfiguration {
    
    @Bean
    public CookieSerializer cookieSerializer() {
        DynamicCookieMaxAgeCookieSerializer serializer = new DynamicCookieMaxAgeCookieSerializer();
        serializer.setCookieName("JSESSIONID");
        serializer.setDomainName("localhost");
        serializer.setCookiePath("/");
        serializer.setCookieMaxAge(3600);
        serializer.setSameSite("Lax");  // 设置SameSite属性
        serializer.setUseHttpOnlyCookie(true);
        serializer.setUseSecureCookie(false);
        return serializer;
    }
}

首发:https://springboot.io/t/topic/2602

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)
首先在shiro配置类中注入rememberMe管理器!复制代码(https://oscimg.oschina.net/oscnet/675f5689159acfa2c39c91f4df40a00ce0f.gif)/cookie对象;rememberMeCookie()方法是设置Cookie的生成模
Stella981 Stella981
2年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Easter79 Easter79
2年前
SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)
首先在shiro配置类中注入rememberMe管理器!复制代码(https://oscimg.oschina.net/oscnet/675f5689159acfa2c39c91f4df40a00ce0f.gif)/cookie对象;rememberMeCookie()方法是设置Cookie的生成模
Stella981 Stella981
2年前
HTML5新增input标签属性
一.inputtype属性1<formaction""2邮箱<inputtype"email"name""id""<inputtype"submit"value"提交"<br/<br/3手机号码<inputtype"tel"name
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k