Firebase:通过 REST 获取令牌并使用 signInWithCustomToken

Posted

技术标签:

【中文标题】Firebase:通过 REST 获取令牌并使用 signInWithCustomToken【英文标题】:Firebase: Getting a token via REST and using signInWithCustomToken 【发布时间】:2018-01-19 09:52:19 【问题描述】:

我正在尝试了解使用令牌的 Firebase 自定义身份验证方法,但文档对我来说并不是那么清楚。在我尝试使用 JWT 生成器之前,我想检查是否有办法使用身份验证响应令牌通过 javascript 登录 Web 客户端:

1) 首先,在 Bash 中:

curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=[theapikey]' -H 'Content-Type: application/json' --data-binary '"email":"[the-user-email]","password":"[the-user-valid-password]","returnSecureToken":true'

2) 回应:


 "kind": "identitytoolkit#VerifyPasswordResponse",
 "localId": "<theresponse-localid>",
 "email": "<theresponse-user-email>",
 "displayName": "<theresponse-displayname>",
 "idToken": "<theresponse-idtoken-string>",
 "registered": true,
 "refreshToken": "<theresponse-refreshToken>",
 "expiresIn": "3600"

3) 所以我将结果复制到一个 JavaScript 对象中:

var token = 
 "kind": "identitytoolkit#VerifyPasswordResponse",
 "localId": "<localid-string>",
 "email": "<user-email>",
 "displayName": "<user-displayname>",
 "idToken": "<idtoken-string>",
 "registered": true,
 "refreshToken": "<refreshtoken-string>",
 "expiresIn": "3600"
;

4) 我已经尝试了其中的每一个来尝试使用该令牌进行验证:

firebase.auth().signInWithCustomToken(token).catch(function(error) 
    console.log("firebase.auth().signInWithCustomToken() Error: ");
    console.log(error);


firebase.auth().signInWithCustomToken(JSON.stringify(token)).catch(function(error) 
    console.log("firebase.auth().signInWithCustomToken() Error: ");
    console.log(error);


firebase.auth().signInWithCustomToken(token.idToken).catch(function(error) 
    console.log("firebase.auth().signInWithCustomToken() Error: ");
    console.log(error);

5) 对于每一个,我都会收到同样的错误:

"Object  code: "auth/invalid-custom-token", message: "The custom token format is incorrect", stack: "" "

我显然弄错了,但我阅读的大多数文档都描述了创建自定义 JWT 令牌。恐怕我还不明白。

【问题讨论】:

您的具体问题是什么? 我希望使用 REST api 生成一个令牌,我可以在 JavaScript 中使用该令牌通过 firebase.auth().signInWithCustomToken(token) 对用户进行身份验证 【参考方案1】:

如果你想signInWithCustomToken,你需要创建一个用你的私钥签名的 JWT。 Firebase Admin SDK 提供了该功能:https://firebase.google.com/docs/auth/admin/create-custom-tokens

这将在您的服务器上运行,然后您将自定义令牌发送到客户端并登录:

firebase.auth().signInWithCustomToken(token).catch(function(error) 
  console.log("firebase.auth().signInWithCustomToken() Error: ");
  console.log(error);
);

【讨论】:

谢谢 Bojeil,你是对的。我确实设法编写了一个 JWT 类来生成令牌,并且能够在 JavaScript 中使用它。我用这篇文章作为参考:firebase.google.com/docs/auth/admin/… 酷,很高兴我能提供帮助。

以上是关于Firebase:通过 REST 获取令牌并使用 signInWithCustomToken的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有 Firebase SDK(即通过 REST)的情况下生成 FCM 注册令牌?

如何通过 HTTP REST API 访问我的 Firebase 数据库?

将 REST API 用于 id 令牌时对 Firebase 存储进行身份验证

Firebase 不接受从 Google Identity Platform 的 REST API 获取的 JWT:“自定义令牌格式不正确。”

使用 node.js admin sdk 创建令牌时的 Firebase REST 身份验证

Firebase 网络通知没有错误但没有通知