Springboot应用中设置Cookie的SameSite属性,跨域支持

21 篇文章 0 订阅
11 篇文章 0 订阅

reponse设置Header的方式设置cookie,具体代码如下:

ResponseCookie cookie = ResponseCookie.from(CommonConstant.TOKEN_HEADER, oAuth2AccessToken.getValue()) // key & value
                    .httpOnly(true)		// 禁止js读取
                    .secure(true)		// 在http下也传输
//                    .domain("localhost")// 域名
                    .path("/")			// path
                    .maxAge(clientDetails.getAccessTokenValiditySeconds())	// 有效期
                    .sameSite("None")	// 大多数情况也是不发送第三方 Cookie,但是导航到目标网址的 Get 请求除外
                    .build()
                    ;
            // 设置Cookie Header
            response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());

需要注意如果要设置sameSite的值为None,必须得设置secure为true,否则cookie设置不成功。如果设置为Lax,则不需要设置secure。

secure设置为true了后,请求仅支持https请求了,http请求不支持了。

转自:Springboot应用中设置Cookie的SameSite属性 - SpringBoot中文社区 - 博客园

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

所有属性都响应正确 √

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;
	}
}

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot 跨域和 Session Cookie失效问题的解决方法如下: 首先,跨域问题可以通过配置Spring Boot的CORS(跨源资源共享)来解决。在Spring Boot,可以使用注解 `@CrossOrigin` 或在配置类添加 `addCorsMappings` 方法来配置跨域的访问。 @CrossOrigin 注解可以应用在控制器类或方法上,指定允许跨域的来源、方法、头部、是否允许携带凭证(比如 Cookie)等参数。例如: ```java @CrossOrigin(origins = "http://localhost:8080", maxAge = 3600, allowCredentials = "true") @GetMapping("/example") public ResponseEntity<String> getExample() { // ... } ``` 另一种配置跨域的方法是创建配置类,并继承 `WebMvcConfigurer` 接口,并重写其 `addCorsMappings` 方法。例如: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST") .allowCredentials(true) .maxAge(3600); } } ``` 其次,Session Cookie失效问题可以通过在跨域请求添加凭证(Credentials)来解决。具体来说,可以将 `allowCredentials` 参数设置为 `true`,同时在请求头添加 `withCredentials: true`。例如: ```javascript fetch('http://localhost:8080/api/example', { method: 'GET', credentials: 'include' // 或 'same-origin' }) ``` 这样配置后,Spring Boot就可以正常接收带有 Cookie跨域请求,并在服务端保持 Session 的有效性。 综上所述,通过配置跨域设置和同时在请求添加凭证,可以解决Spring Boot跨域和Session Cookie失效的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值