javascript - Firebase:通过 REST 获取 token 并使用 signInWithCustomToken

标签 javascript firebase oauth firebase-authentication jwt

我试图了解使用 token 的 Firebase 自定义身份验证方法,但文档对我来说并不是那么清楚。在尝试使用 JWT 生成器之前,我想检查是否有一种方法可以使用身份验证响应 token 通过 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) 我已经尝试了其中的每一个来尝试使用该 token 进行验证:

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 token 。恐怕我还不明白。

最佳答案

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

这将在您的服务器上运行,然后您将自定义 token 发送到客户端并使用以下方式登录:

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

关于javascript - Firebase:通过 REST 获取 token 并使用 signInWithCustomToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45625712/

相关文章:

javascript - 使用 Javascript 的倒计时器

javascript - 使用 Tabulator 设置最大表格高度

javascript - 在 Mozilla Firefox 中使用 moment.js 时获取日期中的无效日期

javascript - 如何避免传单 javascript 库中多个 MultiPolygon GeoJSON 层重叠?

firebase - 如何处理 Firebase Web 中的身份验证/参数错误?

ios - 有什么办法可以让 GCM 与 Firebase SDK v3.3 一起使用吗?

java - Firebase 用户 == 始终为 null

oauth - 使用 Keycloak 和 .NET 核心的基于角色的授权

java - 如何使用java从OpenID + OAuth的请求 token 获取访问 token

asp.net - 使用 OWIN oAuth 中间件(具有单独的身份验证和资源服务器)时,我收到 "Authorization has been denied for this request."错误消息