Vercel 生产分支正在将 POST 上的授权 header 剥离到无服务器功能 API

Vercel Production Branch is stripping Authorization header on POST to Serverless Function API

API 没什么特别的,但我有一个无服务器函数 POST API,它需要一个授权 header 来验证然后写入数据库。

例如:

     curl --location --request POST 'https://myserver.server.com/api/endpoint' \
        --header 'Authorization: Bearer blahblahblahblah'

在 Vercel 预览分支中,我能够让它工作,并且 Authorization header 按预期传递到我的 API。当我在生产中对此进行测试时,Authorization header 从请求中删除(通过记录原始请求 headers 来计算)。关于 Authorization header,预览版和正式版有什么区别?我需要做什么才能在生产中转发 header?

如有任何帮助,我们将不胜感激。提前致谢!

这似乎是 Vercel 中的一个错误(支持已经通知)所以让我们等待他们说什么。我假设他们自己消耗了 authorization header 并随后将其丢弃。这有点奇怪,这只发生在 PROD 中,但我们将会看到。

解决方法

幸运的是,对于我们来说,这很容易解决。我已经发布了我的更新功能来说明这一点。主要是用any header 除了authorization

我正在使用 x_authorization,但名称完全是任意的。

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === 'POST') {
    //using 'custom' x_authorization header because the regular 'authorization' header is stripped by Vercel in PROD environments.
    const { x_authorization } = req.headers

    if (x_authorization === `Bearer ${process.env.CRON_API_KEY}`) {
      
      //TODO: YOU DO YOUR THING HERE!!!

      res.status(200).json()
    } else {
      res.status(401).end()
    }
  } else {
    res.setHeader('Allow', 'POST')
    res.status(405).end('Method Not Allowed')
  }
}

我刚遇到这个问题,我想我找到了它只影响您的生产的原因,或多或少是根本原因。好像跟vercel的转发规则有关

当我将请求发送到 mydomain.com 时,身份验证 header 被删除,但是当我发送到 www.mydomain.com the header remained there. This makes sense because I have the "recommended" forwarding rules from vercel that forwards mydomain.com to www.mydomain.com