在使用授权承载请求时获取Firebase函数中的令牌

时间:2018-05-24 05:49:39

标签: node.js firebase http-headers firebase-authentication google-cloud-functions

我目前正在使用Firebase功能v1.0.3和Firebase管理员v5.12.1。它似乎与express NodeJS库一起正常工作。

问题

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

Authorization: Bearer <token>

它没有显示我的令牌的任何日志。当我在Firebase函数Bearer文件中使用Authorization Bearer来获取console.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-bearerexpress-bearer-token等库,我仍然无法抓住idToken

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

问题

如何使用Express或使用NodeJS的任何方法捕获Firebase函数内的令牌?

1 个答案:

答案 0 :(得分:1)

授权持有人工作。以下是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中的相同文档,仅当corscookiescookie-parser插件且req.headers.authorization完全相同时才能完全有效已启用并已发送到firebase-functions端点。

相关问题