添加 JWT 身份验证后 CORS 不起作用

CORS don't work after JWT authentication added

我有一个 Vue 前端、一个 Auth0 和 Fastify 后端。 CORS配置如下:

fastify.register(require('fastify-cors'), {
  origin: 'http://localhost:8080',
  methods: 'GET,PUT,POST,DELETE,OPTIONS,HEAD',
  allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
})

前端headers配置:

this.$auth.getTokenSilently().then(token => {
  this.headers = {
    Authorization: `Bearer ${token}` // send the access token through the 'Authorization' header
  };

常见问题:

Access to XMLHttpRequest at 'http://127.0.0.1:3000/dir' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我读了很多关于 CORS 的文章,知道这是浏览器端的问题(Insomnia 完美地发送请求)。实际上,我不清楚我还应该允许什么以及如何允许。基本上我只需要允许标准的 GET、PUT、POST、DELETE 请求。您能否指出我的代码中的确切配置问题?

  1. 第一个 401 是由没有验证令牌的 OPTIONS 请求引起的。实际上它应该被fastify-cors无缝处理。但是由于 on-request 挂钩的初始化顺序不正确(首先 - 我要使用 fastify-auth0-verify 进行验证,第二 - 来自 [ 的隐式挂钩=42=]),它从未被调用过。所以你需要一个精确的挂钩顺序显式和隐式初始化:first - cors,然后 second - authentication.
  2. 第二个问题,POST 之后的 401,是由于在前端 Vue 端错误使用 axios 请求参数而发生的。 Headers 像 { Authorization: 'Bearer SomeVeryLongSecretXYZ'} 被传递为,例如 ...post(url, data, this.headers),但必须有 {headers : this.headers}.
  3. CORS 的最终配置:

fastify.register(require('fastify-cors'), {
  origin: '*',
  methods: 'GET,PUT,POST,DELETE,OPTIONS',
})