单点登录-跨域写cookie的实现

不多说,上代码:

前端页面,地址示例:https://a.com/index.html,代码:

<!DOCTYPE html>
<html charset="utf-8">
<head>
	<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
	<button id="login">登录</button>
</body>
<script type="text/javascript">
	$(document).ready(function(){
		$("#login").click(function(){
			$.ajax({
				url: 'https://t.a.com/test1.php',
				type: 'GET',
				success: function (data) {
					/** 在test1.php中或此处写cookie */
					$.ajax({
						/** 这里只是一个演示,在项目中需要有验证 */
						url: "https://t.b.com/test2.php",
						type: "GET",
						dataType: "jsonp", //指定服务器返回的数据类型
						success: function (data) {
							
						}
					});
				}
			});
		});
	});
</script>
</html>

test1.php

<?php
//随便写就好了,状态码是200就OK

test2.php,这里是跨域访问,有些代码被注释了,这里用不到。

<?php 
// 指定允许其他域名访问
header("Access-Control-Allow-Origin: *");
// 是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回
header("Access-Control-Allow-Credentials: true");
// 允许的请求头字段
// header("Access-Control-Allow-Headers: *");
/** Set-Cookie由服务器发送,它包含在响应请求的头部中。它用于在客户端创建一个Cookie
  * SameSite的值可以设置为3种:Strict Lax None
  * 其中Strict最为严格,如果设置为Strict,上表的方式均无法附带Cookie。Lax稍微宽松点,设置为Lax,会限制部分请求。
  * 当设置为None的时候表示关闭不启用SameSite防护。	
	*/
header("Set-Cookie: admin=demo; secure=true; path=/; domain=b.com; SameSite=None");

需要特别注意的地方:

1、一定要是HTTPS请求;  

2、实际项目中一定要有验证。

 

posted @ 2021-06-23 14:22  沙漠海123  阅读(323)  评论(0编辑  收藏  举报