编程语言/http/HEAD/Cookie 跨域:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == 如果验证登陆状态,大略有两种方法:cookie/session、token。 其中 token 的机制是通过 header 响应头设置诸如 x-token 的…”
 
Kangkk​(留言 | 贡献)
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”
标签:ReplaceText 移动版编辑 移动版网页编辑
 
(未显示同一用户的12个中间版本)
第1行: 第1行:
== 引言 ==
{{sign}}
如果验证登陆状态,大略有两种方法:cookie/session、token。
==引言==
如果验证登陆状态,大略有两种方法:cookie/session、token。(先假定后端网址:testapi.kangjian.xyz,前端网址:localnode.kangjian.xyz)


其中 token 的机制是通过 header 响应头设置诸如 x-token 的字段,eq:
其中 token 的机制是通过 header 响应头设置诸如 x-token 的字段,eq:
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript" highlight="12">
Response Headers
Response Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
第21行: 第22行:


如果是 cookie 机制,就需要后端在响应头中设置 set-cookie 字段,eq:
如果是 cookie 机制,就需要后端在响应头中设置 set-cookie 字段,eq:
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript" highlight="11">
Response Headers
Response Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
第51行: 第52行:
   res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, x-token, x-cl , x-did, x-info, x-v, Accept,X-Requested-With");
   res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, x-token, x-cl , x-did, x-info, x-v, Accept,X-Requested-With");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials","true");
   res.header("X-Powered-By",' 3.2.1')
   res.header("X-Powered-By",' 3.2.1')
   res.header("Content-Type", "application/json;charset=utf-8")
   res.header("Content-Type", "application/json;charset=utf-8")
第62行: 第62行:
这样接口跨域跑通,之后是 cookie 跨域,找到文档规范 [https://tools.ietf.org/html/rfc6265#section-4.1 rfc6265] 中规定,cookie 跨域忽略端口,在设置 domain 为一级主域名之后(或 <code>www.一级域名</code>),子域名之间可以操控 cookie。
这样接口跨域跑通,之后是 cookie 跨域,找到文档规范 [https://tools.ietf.org/html/rfc6265#section-4.1 rfc6265] 中规定,cookie 跨域忽略端口,在设置 domain 为一级主域名之后(或 <code>www.一级域名</code>),子域名之间可以操控 cookie。


 
在后端代码设置简单的 set-cookie 方法,这里有一个很关键的 header 响应头字段是 <code>res.header("Access-Control-Allow-Credentials", "true");</code>。
<syntaxhighlight lang="javascript">
{{hc|router/index.js|<syntaxhighlight lang="javascript">
router.get('/',function(req, res, next) {
router.get('/',function(req, res, next) {
   var result = {'dd':"cc"};
   var result = {'dd':"cc"};
第71行: 第71行:
   })
   })
   res.json(result);
   res.json(result);
})</syntaxhighlight>}}
然后在前端页面请求后端接口时,一定要附带 <code>withCredentials = true</code>,我这里的项目是 nuxt,所以自带 @nuxt/axios。(这里有一个坑,我看了许多示例项目和网络帖子,发现很多人都是重新 npm install axios 而不是使用内置的 @nuxt/axios,这两者本质并没有区别,况且多加一个 axios 不冗余嘛,@nuxt/axios 已经完全够用了,axios 支持的 @nuxt/axios 也完全支持,不管是走 nuxt.config.js 里的 plugins 还是页面组件直接直连,都可以 hold 住。)
这里再简说一下我这边的 @nuxt/axios 设置,<code>plugins/axios.js</code> 组件扩展 @nuxt/axios,拦截请求头和响应头。这里着重说 <code>withCredentials = true</code>。在 @nuxt/axios 中已经内置参数 <code>credentials: true</code> (默认值 false),表示在请求中自动添加 <code>withCredentials = true</code>,<code>credentials: true</code> 需要在 nuxt.config.js 配置文件中的 <code>axios</code> 对象中设定,如果设定了这个值,那么所以从这里开始,不再需要添加 <code>withCredentials = true</code>,'''前提是 @nuxt/axios 的 baseURL 地址与接口地址一致'''。
以下,我展示调用接口的示例(自己写的架构,还有瑕疵):
{{hc|pages/search/listLeft,vue|<syntaxhighlight lang="javascript">
import { TestSetCookie } from '@@/api/test'
...
  methods: {
    ...
      // 测试 coookie 跨域
      new TestSetCookie(this.$axios)
      .fetch('GET')
      .then(value => {
        console.log(value)
      })
</syntaxhighlight>}}
{{hc|api/test.js|<syntaxhighlight lang="javascript">
import { localTest } from '@/config/conf'
export class TestSetCookie {
  constructor ($axios, context){
    this.$axios = $axios;
    this.context = context;
  }
  async fetch (type) {
    const result = await this.$axios.call(null, {
      method: type || 'POST',
      url: localTest.textSetCookie,
    })
    // 返回值处理等
    return result
  }
}</syntaxhighlight>}}
{{hc|config/conf.js|<syntaxhighlight lang="javascript">
let host = process.env.host
// 开发环境客户端请求 api 代理
let proxyTable = host.proxyTable
for (let key in proxyTable) {
  let targetHost = proxyTable[key].targetHost
  if (targetHost) {
    if (proxyTable[key].ifProxy && process.env.NODE_ENV === 'development') {
      host[targetHost] = key
    } else {
      host[targetHost] = proxyTable[key].target
    }
  }
}
...
/**
* 自测模块
*/
export const localTest = {
  textSetCookie: `${host.appLocalTestHost}/test`, // 后端测试接口
}</syntaxhighlight>}}
{{hc|config/net.js|<syntaxhighlight lang="javascript">
export default {
  development:{
    target:{
      '/LOCAL': {
        targetHost: 'appLocalTestHost',
        target: 'http://testapi.kangjian.xyz',
        secure: false,
        changeOrigin: true,
        pathRewrite: { '^/LOCAL': '' },
        ifProxy: false
      },
      '/SEARCH': {
        targetHost: 'appSearchHost',
        target: 'http://localnode.kangjian.xyz/searchapi',
        secure: false,
        changeOrigin: true,
        pathRewrite: { '^/SEARCH': '' },
        ifProxy: false
      },
      '/APP': {
        targetHost: 'appHost',
        changeOrigin: true,
        target: 'http://local.kangjian.xyz:8086',
        pathRewrite: { '^/APP': '' },
        ifProxy: false
      }
    },
    staticHost: `/_nuxt/`,
    cloudStaticHost: `http://static.kangjian.xyz`,
  },
</syntaxhighlight>}}
{{hc|config/env.js|<syntaxhighlight lang="javascript" highlight="43,44">
import netConfig from './net'
/**
* 由 npm 传值,如 npm run build --target=production,npm_config_target 为 production
* @desc production、beta、gray、alpha、test
* @type {string|string}
*/
export const target = process.env.npm_config_target || 'development'
/*
const prefix = target === 'production' ? '' : target
const protocol = ~['production', 'beta', 'gray'].indexOf(target) ? 'https:' : 'http:'
*/
let map = {
  proxyTable: {
  },
  staticHost: ``
}
Object.keys(netConfig).forEach(function (key){
  if(key === target){
    map.proxyTable = netConfig[key].target
    map.staticHost = netConfig[key].staticHost
    map.cloudStaticHost = netConfig[key].cloudStaticHost
  }
})
export const host = map</syntaxhighlight>}}
{{hc|plugins/axios.js|<syntaxhighlight lang="javascript">
import { Loading } from 'element-ui'
import { stringify } from 'qs'
import { getType } from './utils'
import { whetherString } from './type'
import { httpCode, httpStatus } from '@@/config/httpCode'
export default ({ $axios, redirect, $cookies, router, store }) => {
  let ElementUiLoading = null
  let token = null
  if(process.server){
    // 获取服务端的token
  }
  if(process.client){
    // 获取客户端token
    token = $cookies.get('x-token');
  }
  $axios.create({
    timeout: 8000,
  })
  // $axios.defaults.withCredentials = true
  // $axios.defaults.baseURL = 'http://testapi.kangjian.xyz'
  /**
  * request 拦截器
  * @desc 将获取到 token 加入到请求头中
  */
  $axios.interceptors.request.use(
    (config) => {
      if(process.client){
        /**
        * 页面加载状态
        * @type {ElLoadingComponent}
        */
        ElementUiLoading = Loading.service({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)',
          customClass:"osloading",
          fullscreen: true
        })
      }
      // 动态设置baseurl
      config.baseURL = config.url.replace(/(http[s]{0,1}:\/\/[a-zA-Z0-9.-]+)?.*/i,'$1')
      config.headers['x-token'] = token;
      return config
    },
    (error) => {
      ElementUiLoading.close()
      return Promise.reject(error)
    });
  /**
  * response 拦截器
  */
  $axios.interceptors.response.use(
    (response) => {
      if(process.client){
        ElementUiLoading.close()
      }
      console.log(response.headers)
      // if(response.status) httpStatus(response.status)
      const reqCode = (response && response.data && response.data.code)
        ?whetherString(response.data.code)
          ?response.data.code
          :(String(response.data.code))
        :6000
      return httpCode(reqCode).status?response.data.data:[]
    },
    (error) => {
      if(process.client){
        ElementUiLoading.close()
      }
      return Promise.reject({ code: '-100', message: `网络异常请稍后再试!${error}` })
    })
}
</syntaxhighlight>}}
这样设置就将 baseURL 动态设置为即将请求的接口的地址网址,然后 cookie 跨域成功。
在这里要实现三个统一、一个动态。即统一管理代理、统一管理接口、统一处理接口请求和返回值过滤,一个动态是指动态赋值 @nuxt/axios 的 baseURL 参数。
[[文件:Header setcookie eq jiekou 1.png|none|700px|左|Header setcookie eq jiekou 1]]
在实际项目中设置 set-cookie 有一些容易忽略的细节。
比如有很多人说 chrome 浏览器的 set-cookie 的 samesite 字段和 secure 字段,如果设置了 samesite=none,则必须同时设置 secure,然后接口走 https:443,才可以,eq:
<pre>
Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/; samesite=none; secure
</pre>
但是这里有一个问题是 express 框架的 res.cookie方法遵循 [https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1 draft-ietf-httpbis-cookie-same-site-00] 规范,只有 <code>Strict</code> 和 <code>Lax</code> 值,没有 <code>none</code>。所以想要设置 <code>samesit=none</code>,要在 nginx 服务上进行代理
<syntaxhighlight lang="javascript">
location / {
...
  proxy_cookie_path / "/; httponly; secure; SameSite=none";
}</syntaxhighlight>
生成的响应头中 set-cookie 变更为
{{Double-columns|<syntaxhighlight lang="javascript">
Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/;</syntaxhighlight>
|<syntaxhighlight lang="javascript">
Set-Cookie: user=kangkk; Domain=kangjian.xyz; Path=/; httponly; secure; SameSite=none</syntaxhighlight>
}}
同时这一行字段抛错:this set-cookie was blocked because it had the secure attribute but was not received over a secure connection.(没有使用 https)
并且 cookie 并没有写入 application。所以在后端设置 samesite 为 false 最合适(在不使用 https 的情况下)。
两外需要注意的地方是 mock.js 与 xhr.js 的区别,如果使用了 mock.js (mock.js 没有注释掉),则需要改 mock.js (并非 mock 源码,而是 mock 的应用逻辑文件)
<syntaxhighlight lang="javascript">
import Mock from 'mockjs'
Mock.XHR.prototype.withCredentials = true
Mock.mock(/\/demo\/test/,{
...
})</syntaxhighlight>
})</syntaxhighlight>


==其他==


在实际项目中设置 set-cookie 有一些容易忽略的细节。
浏览器(谷歌浏览器)在地址栏输入 [chrome://flags/ chrome://flags/],选择 <code>SameSite by default cookies</code> 和 <code>Cookies without SameSite must be secure</code> 选项