我试图了解使用 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/