我正在尝试使用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
上执行此操作,这给了我在浏览器中打印的令牌testCustomLogin
,然后将步骤2中的令牌作为参数传递。在网络流量中,我看到对/logincookiesession
的呼叫返回了此消息:
UNAUTHORIZED REQUEST!{"code":"auth/invalid-id-token","message":"The provided ID token is not a valid Firebase ID token."}
我完全迷路了。
我可以在firebase控制台的“身份验证”部分中看到已创建并登录了用户jcm@email.com
,但是无法创建会话cookie。
请,我在这里需要一些建议。
答案 0 :(得分:0)
创建cookie会话的路由出错。
它应该这样开始。
aNumber = nf.format(new Double(aNumber));
我使用的代码来自手册OMG。我希望这也会对某人有所帮助。