javascript - firebase 身份验证:signInWithCustomToken 和 createSessionCookie - 错误 auth/invalid-id
问题描述
我正在尝试使用 Firebase 自定义令牌和会话 cookie 实现登录机制,当然我做错了什么,但我无法弄清楚。
我将放置我的代码,然后解释我如何使用它来测试它。
前端代码
const functions = firebase.functions();
const auth = firebase.auth();
auth.setPersistence(firebase.auth.Auth.Persistence.NONE);
auth.onAuthStateChanged((user) => {
if (user) {
user.getIdToken()
.then((idToken) => {
console.log(idToken);
});
}
});
function testCustomLogin(token) {
firebase.auth().signInWithCustomToken(token)
.then((signInToken) => {
console.log("Login OK");
console.log("signInToken", signInToken);
signInToken.user.getIdToken()
.then((usertoken) => {
let data = {
token: usertoken
};
fetch("/logincookiesession", {
method: "POST",
body: JSON.stringify(data)
}).then((res) => {
console.log("Request complete! response:", res);
console.log("firebase signout");
auth.signOut()
.then(()=> {
console.log("redirecting ....");
window.location.assign('/');
return;
})
.catch(() => {
console.log("error during firebase.signOut");
});
});
});
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
});
}
后端代码
app.post('/logincookiesession', (req, res) => {
let token = req.body.token;
// Set session expiration to 5 days.
const expiresIn = 60 * 60 * 24 * 5 * 1000;
// Create the session cookie. This will also verify the ID token in the process.
// The session cookie will have the same claims as the ID token.
// To only allow session cookie setting on recent sign-in, auth_time in ID token
// can be checked to ensure user was recently signed in before creating a session cookie.
admin.auth().createSessionCookie(token, {expiresIn})
.then((sessionCookie) => {
// Set cookie policy for session cookie.
const options = {maxAge: expiresIn, httpOnly: true, secure: true};
res.cookie('session', sessionCookie, options);
res.end(JSON.stringify({status: 'success'}));
})
.catch((error) => {
res.status(401).send('UNAUTHORIZED REQUEST!' + JSON.stringify(error));
});
});
app.get('/logintest', (req, res) => {
let userId = 'jcm@email.com';
let additionalClaims = {
premiumAccount: true
};
admin.auth().createCustomToken(userId, additionalClaims)
.then(function(customToken) {
res.send(customToken);
})
.catch(function(error) {
console.log('Error creating custom token:', error);
});
});
所以基本上我所做的是
- 执行
firebase emulators:start
- 在我的浏览器上手动执行此操作
http://localhost:5000/logintest
,这给了我一个打印在浏览器中的令牌 - 然后在另一个页面中,我有登录表单,我打开浏览器的 javascript 控制台并执行我的 javascript 函数
testCustomLogin
,并将步骤 2 中的令牌作为参数传递。
在网络流量中,我看到/logincookiesession
返回这个的调用:
UNAUTHORIZED REQUEST!{"code":"auth/invalid-id-token","message":"The provided ID token is not a valid Firebase ID token."}
我完全迷路了。
我可以在 firebase 控制台的 Authentication 部分看到用户jcm@email.com
已创建并登录,但我无法创建 session-cookie。
拜托,我在这里需要一些建议。
解决方案
创建 cookie 会话的路径出错。
它应该像这样开始。
app.post('/logincookiesession', (req, res) => {
let params = JSON.parse(req.body);
let token = params.token;
我使用的代码来自手册,OMG。我希望这对某人也有帮助。