首页 > 解决方案 > 使用授权承载请求时在 Firebase 函数中获取令牌

问题描述

我目前正在使用 Firebase Functionsv1.0.3和 Firebase Admin v5.12.1。它似乎与expressNodeJS 库一起工作正常。

问题

但是,当我尝试通过发送 Authorization 标头来保护请求时:

Authorization: Bearer <token>

它没有显示我的令牌的任何日志。当我在Firebase FunctionsBearer文件中使用来获取.Authorization Bearerconsole.log(request)index.jstoken

req.headers我从使用时得到的只是以下内容console.log

{ 'content-length': '0',
  'accept-language': 'en-US,en;q=0.9',
  'accept-encoding': 'gzip, deflate, br',
  referer: 'http://localhost:5000/admin/',
  accept: '*/*',
  'access-control-request-headers': 'authorization,content-type',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
  origin: 'http://localhost:5000',
  'access-control-request-method': 'GET',
  connection: 'close',
  host: 'localhost:5001' 
}

文档来源

我已阅读有关Firebase Functions Samples: Authorized HTTPS Endpoint示例代码的文档,其中一些似乎已过时。

firebase.auth().currentUser.getToken()

比如现在是:

firebase.auth().currentUser.getIdToken()

其他库

我尝试安装诸如express-authorization-bearerand之类的库express-bearer-token,但我仍然无法捕获idToken.

我想知道这是 NodeJS 问题还是 Firebase Functions 问题。我目前正在使用 NodeJSv6.11.4

问题

如何使用 Express 或任何使用 NodeJS 的方法在 Firebase Functions 中捕获令牌?

标签: node.jsfirebasehttp-headersfirebase-authenticationgoogle-cloud-functions

解决方案


授权持有人工作。这是我时的结果console.log(req.headers)

{ 'accept-language': 'en-US,en;q=0.9',
  'accept-encoding': 'gzip, deflate, br',
  referer: 'http://localhost:5000/admin/',
  accept: '*/*',
  'content-type': 'application/json',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
  origin: 'http://localhost:5000',
  authorization: 'Bearer something',
  connection: 'close',
  host: 'localhost:5001' }

在这种情况tokensomething

重要笔记:

  • req.headers.authorization不适用于Assigning Multiple Origins,因为它给出了错误Cannot set headers after they are sent,但它应该通过允许任何来源并cors作为中间件轻松工作:

    var cors = require('cors')({origin: true}); app.use(cors);

    无论如何,req.headers.authorization它已经在保护它了。

  • req.headers.authorization不能赋值给参数,否则会变成undefined

  • 使用来自Authorized HTTPS Endpoints的相同文档,它应该完全工作,仅当cors, cookieswith cookie-parserplugin, 并且req.headers.authorization完全启用并发送到firebase-functions端点。


推荐阅读