node 第十一天 纯使用第三方cookie 实现 跨源单点登录(或者说免登录) 以及白话说cookie的跟踪原理

编程入门 行业动态 更新时间:2024-10-10 10:26:34

node 第十一天 纯使用第三方cookie 实现 跨源<a href=https://www.elefans.com/category/jswz/34/1767343.html style=单点登录(或者说免登录) 以及白话说cookie的跟踪原理"/>

node 第十一天 纯使用第三方cookie 实现 跨源单点登录(或者说免登录) 以及白话说cookie的跟踪原理

1. 白话说cookie跟踪, 广告推送基础原理
第三方cookie
首先第三方要在第一方设置cookie, 必要条件是两方互相同意
天猫和淘宝是两个域名 天猫决定可以设置淘宝的cookie, 比如去请求一个淘宝的接口 [注释1] (这里反映了第一方的同意)
访问者访问天猫, 同时设置上了一个淘宝的cookie ;设置第三方cookie本质上是后端设置的,因为js设置cookie是不能指定domain为第三方源的(这里需要后端设置cookie, 第三方设置cookie必须同时指定 SameSite=None; Secure)因为是第三方给第一方设置cookie 这里反映了第三方的同意
例如 :
1 登录天猫时 设置一个淘宝cookie user: li 这样就知道了你的用户名
2 在天猫上买了一瓶水 又设置一个淘宝的cookie buy: water 这样就知道你渴了要买水
然后你去登录淘宝, 带上已经有的淘宝域下cookie, 既然访问的是淘宝, 那当然可以带上淘宝自己的cookie
淘宝就知道你的用户名, 你要买水, 给你推多多的水

注释1: 请求第三方接口, 例如:

  • 可以通过ajax(需要处理跨域, 和cookie许可, 如果只是为了设上第三方cookie一般不这么做)
  • 请求一张第三方图片, 第三方做相应操作
  • 请求一个第三方js文件 (百度统计的做法)

2.设想一个单点登录需求
我有两个网站A(http://127.0.1.1:5500)和B(http://127.0.4.1:5500), 我的服务器是http://127.0.1.1:3007, , 用户只要登录B网站, 就不需要再登录A网站了(A或B网站的登录接口都是访问一个服务器), 这是一个单点登录的特例

  • 前置知识一, 对浏览器来说,cookie是区分域,不区分端口的,
  • 前置知识二, 标记为 secure 的 Cookie 只应通过被 HTTPS 协议加密过的请求发送给服务端。它永远不会使用不安全的HTTP 发送(本地主机除外) 本文所用的ip都是本地主机ip
  • 同一个ip地址下多个端口的cookie是共享的, 意味着我只要登录过B网站, 然后服务器端往B网站设置一个cookie,设置cookie的过程可以是, B请求服务器的登录接口, 然后服务器做相应操作, 显然这个cookie的域肯定是服务器的源127.0.1.1, 这样就成功在B上设置上了第三方cookie, 当我访问A时, A和服务器除了端口是同源的, 访问登录接口时会带上我在B设置的源为127.0.1.1的cookie, 携带了这个cookie我的服务器就让用户免登录.
  • 这么一来流程就通了~
  • 什么? 你想用户登录过A也可以免登录B, 换个思维, 你让A的登录接口请求服务器http://127.0.4.1不就可以了吗 ! ! !

3.下面是演示代码 (代码处理跨域的思路在第九天已经说了, 代码也是第九天的改造)
node.js 服务端代码

const fs = require('fs');
const url = require('url');
const http = require('http');
const querystring = require('querystring');
const path = require('path');const server = http.createServer((req, res) => {if (['http://127.0.1.1:5500', 'http://127.0.4.1:5500'].includes(req.headers['origin'])) {res.setHeader('Access-Control-Allow-Origin', req.headers['origin']);}res.setHeader('Access-Control-Allow-Headers', 'Content-Type, x-token');res.setHeader('Access-Control-Allow-Credentials', 'true');res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS, DELETE');res.setHeader('Access-Control-Max-Age', 1728000); //预请求缓存20天if (req.method === 'OPTIONS') {res.writeHead(200);res.end();} else {let cookie = req.headers.cookie;cookie = cookie?.replace(/\s/g, '');const cookieInfo = querystring.parse(cookie ?? '', ';');//有cookie直接免登录if (cookieInfo.token === '10086') {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 1, data: { name: 'jian' }, msg: '登录成功' }));} else if (req.url === '/login') {req.on('data', chunk => {let { pw } = JSON.parse(chunk.toString('utf-8'));if (pw === '123456') {let date = new Date();date.setDate(date.getDate() + 1);let expires = date.toUTCString();//这里设置第三方cookieres.writeHead(200, {'content-type': 'application/json','set-cookie': [`token=10086; Expires=${expires}; SameSite=None; Secure`]});res.end(JSON.stringify({ code: 1, data: { name: 'jian' }, msg: '登录成功' }));} else {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 0, data: {}, msg: '密码错误' }));}});} else {res.writeHead(200, {'content-type': 'application/json'});res.end(JSON.stringify({ code: 0, data: {}, msg: '未登录' }));}}
});
server.listen(3007, '127.0.1.1');

4.网站A和网站B代码, 运行在不同的源(origin)下

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>ajaxCookie</title></head><body><div id="login" style="display: none"><h1>请登录:</h1><input id="password" name="pw" type="password" /><input id="submit" type="submit" value="登录" /></div><div id="content" style="display: none"><h1>欢迎您~</h1></div></body><!-- <script src="http://127.0.1.1:3007/jsonp"></script> --><script>function myAjax({method = 'GET',url = '/',data = {},headers = {'content-type': 'application/x-www-form-urlencoded'},responseType = 'text',withCredentials = false,success = res => {console.log(res);},error = err => {console.log(err);}}) {let ajax = new XMLHttpRequest();ajax.withCredentials = withCredentials;ajax.open(method, url);for (const key in headers) {if (Object.hasOwnProperty.call(headers, key)) {ajax.setRequestHeader(key, headers[key]);}}ajax.responseType = responseType;ajax.send(data);ajax.onreadystatechange = () => {if (ajax.readyState === 4) {success(ajax.response);}};ajax.onerror = err => {error(err);};}</script><script>const loginEl = document.querySelector('#login');const submitEl = document.querySelector('#submit');const contentEl = document.querySelector('#content');//前端控制路由function toLogin() {loginEl.style.display = 'block';contentEl.style.display = 'none';}function toContent() {loginEl.style.display = 'none';contentEl.style.display = 'block';}//进入即发起请求(不携带密码, 携带同源cookie)myAjax({method: 'POST',url: 'http://127.0.1.1:3007/ajax',data: JSON.stringify({}),headers: {'content-type': 'application/json','x-token': 'x-token'},responseType: 'json',withCredentials: true,success: res => {console.log(res);if (res.code === 1) {this.toContent();} else {this.toLogin();}},err: err => {console.log(err);}});submitEl.onclick = () => {let pw = document.querySelector('#password').value;myAjax({method: 'POST',url: 'http://127.0.1.1:3007/login',data: JSON.stringify({pw: pw}),headers: {'content-type': 'application/json','x-token': 'x-token'},responseType: 'json',withCredentials: true,success: res => {console.log(res);if (res.code === 1) {this.toContent();} else {this.toLogin();}},err: err => {console.log(err);}});};</script>
</html>

5. 你在B登录后就能免登录A啦 fun:-)

更多推荐

node 第十一天 纯使用第三方cookie 实现 跨源单点登录(或者说免登录) 以及白话说cookie的跟踪原理

本文发布于:2023-12-05 23:36:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1665736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单点   白话   或者说   第三方   原理

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!