跨域与同源策略

  • Same-origin policy也就是同源策略;是为了防止假冒网站冒充源网站,对网站进行了一些限制,主要有 Cookie、LocalStorage 和 IndexDB 无法读取DOM 无法获得AJAX 请求不能发送,同时还规定,提交表单不受同源政策的限制。
  • 最初,它的含义是指,A网页设置的 Cookie,B网页不能打开,除非这两个网页"同源"。所谓"同源"指的是"三个相同"。协议相同(http)、域名相同(www.amazon.com)、端口相同(80);
  • 但有时,我们就需要去跨网站请求,这就需要用到跨域了 Cross-origin resource sharing也就是 CORS 技术;

简单请求:
(1)请求方法是以下三种方法之一:HEAD、GET、POST
(2)HTTP的头信息不超出以下几种字段:
	Accept
	Accept-Language
	Content-Language
	Last-Event-ID
	Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

上面为简单请求,浏览器会添加一个Origin字段表明来自哪个源(协议 + 域名 + 端口)服务器根据这个值,决定是否同意这次请求。

同意后,返回请求头包含Access-Control-Allow-Origin字段(与CORS请求相关的字段,都以Access-Control-开头),它的值要么是请求服务器的字段,要么是 *,代表谁都可以。

非简单请求:
(1)请求方法是PUT或DELETE
(2)Content-Type字段的类型为 application/json

非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)

SameSite 问题

This attempt to set a cookie via a Set-Cookie header was blocked because it was not sent over a secure connection and would have overwritten a cookie with the Secure attribute.

Chrome 51 开始,浏览器的 Cookie 新增加了一个 SameSite 属性,用来防止 CSRF 攻击和用户追踪。这个属性有3个值 [Strict, Lax, None]

简单了解:

  1. Strict (host 相同才使用 Cookie)
  2. Lax (只有跳转链接、预加载和GET请求能发送 Cookie) 前两种基本杜绝了 CSRF 攻击
  3. None (Chrome 将 Lax 作为默认设置, 选择 None + Secure 可以关闭 SameSite 属性)

示例: Set-Cookie: widget_session=abc123; SameSite=None; Secure

  • 服务器端解决, 需要在 https 连接的时候, 设置 Cookie:

response.setHeader(“Set-Cookie”, “HttpOnly;Secure;SameSite=None”);

  • 浏览器端解决:

打开连接

chrome://flags/#site-isolation-trial-opt-out

搜索 same, 关闭下面三个:

  1. Delay the commit to screen for same-origin navigations
  2. SameSite by default cookies
  3. Enable removing SameSite=None cookies

Sessions don’t work in Chrome but do in IE

https://www.petefreitag.com/item/857.cfm

it doesn’t often end up being a difference in the browser implementation, but rather the difference is that the user has essentially cleared their cookies when they try another browser.
它通常不会最终成为浏览器实现的差异,但差异在于用户在尝试其他浏览器时基本上清除了他们的 cookie

end up 最终到达; 结果; 到头来;
but rather 转折 宁可说是、would rather 宁愿、or rather 更精确地说
而 (并列、承接、递进、假设、因果、转折)

Cookie 共享问题 (session共享)

浏览器是根据应用的 域名IP地址 储存 Cookie 的 (如 sessionId ), 相同的 域名或 IP地址, 即使端口不同, 相互之间也会干扰, 造成 session共享的问题 (也就是 A 项目的 sessionId 用到了 B 项目上, 导致 B 项目判断 session 不存在)

解决办法也很简单, 使名称也就是 key (JSESSIONID=xxxxx) 不重复就行了.

SessionId 相关

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

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

server:
	servlet:
		session:
			cookie: # 有五层
				name: identifier # 修改 sessionId 名称
				# 下面两个属性需要在https下设置, 不然设置不了
				same-site: none # 设置SameSite为None
				secure: on # 设置 Secure 属性
  • 不在 https下设置: This attempt to set a cookie via a Set-Cookie header was blocked because it had the “Secure” attribute but was not received over a secure connection.
    在这里插入图片描述

最后显示为: identifier=F74F558466FEAC9152AB05A4CD2942E6; Path=/base; Secure; HttpOnly; SameSite=None

HttpOnly 表明该 cookie 在客户端上不可通过 js 获取, 无法用 document.cookie 打出 cookie 的内容. 这缓解了最常见的 XSS 攻击 (Cross Site Scripting: 跨站脚本攻击 i.e. 盗用 cookie 等)
Secure 属性是说如果一个cookie被设置了Secure=true, 那么这个 cookie 只能用https协议发送给服务器, 用http协议是不发送的

全部属性:

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
  • ResponseCookie
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";
	}
}
  • tomcat 的 session 设定在 tomcat 配置文件里, 设置 sessionCookieName 这个字段修改默认的sessionId 名称
<Context path="/" docBase="webapp" reloadable="false" sessionCookieName="identifier"></Context>
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);
		};
	}
}
  • 通过自定义 CookieSerializer 设置 Spring Session 的 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;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值