这是我的客户端代码:
function signIn(){
var email = document.getElementById("username").value;
var password = document.getElementById("password").value;
// As httpOnly cookies are to be used, do not persist any state client side.
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
// When the user signs in with email and password.
firebase.auth().signInWithEmailAndPassword(email, password).then(user => {
// Get the user's ID token as it is needed to exchange for a session cookie.
return firebase.auth().currentUser.getIdToken().then(idToken => {
// Session login endpoint is queried and the session cookie is set.
// CSRF protection should be taken into account.
// ...
var csrfToken = getCookie('_csrf')
return postIdTokenToSessionLogin('/sessionLogin', idToken, csrfToken);
});
}).then(() => {
// A page redirect would suffice as the persistence is set to NONE.
return firebase.auth().signOut();
}).then(() => {
window.location.assign('/profile');
});
}
我正在发送idToken和csrfToken来生成一个sessionId。使用此sessionId,我可以分配会话cookie。
这是我的服务器端代码:
app.post("/sessionLogin", (req, res) => {
// Get ID token and CSRF token.
var idToken = req.body.idToken.toString();
var csrfToken = req.body.csrfToken.toString();
// Guard against CSRF attacks.
if (!req.cookies || csrfToken !== req.cookies._csrf) {
res.status(401).send('UNAUTHORIZED REQUEST!');
return;
}
// Set session expiration to 5 days.
var 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.
// We could also choose to enforce that the ID token auth_time is recent.
firebase.auth().verifyIdToken(idToken).then(function(decodedClaims) {
// In this case, we are enforcing that the user signed in in the last 5
minutes.
if (new Date().getTime() / 1000 - decodedClaims.auth_time < 5 * 60) {
return firebase.auth().createSessionCookie(idToken, {expiresIn:
expiresIn});
}
throw new Error('UNAUTHORIZED REQUEST!');
})
.then(function(sessionCookie) {
// Note httpOnly cookie will not be accessible from javascript.
// secure flag should be set to true in production.
var options = {maxAge: expiresIn, path: "/", httpOnly: false, secure: true
/** to test in localhost */};
res.cookie('session', sessionCookie, options);
res.end(JSON.stringify({status: 'success'}));
})
.catch(function(error) {
res.status(401).send('UNAUTHORIZED REQUEST!');
});
});
app.get("/profile", (req, res) => {
console.log('Cookies: ', req.cookies); //Empty object, 'Cookies: {}'
res.render("profile");
});
app.post("/profile", (req, res) => {
res.send(req.body.name);
console.log('Cookies: ', req.cookies); //Cookies object with csrf and
session token
});
现在,这可以正常工作,并且我能够在每次POST请求时将cookie传递到服务器。未经身份验证的用户无法发送POST请求。但是,我希望对用户进行身份验证并提供与用户相关的数据。那么,如何使用这些会话cookie来为GET请求提供路由?目前,我的客户端未在GET请求中发送这些Cookie。
我已经遵循了这些Firebase documents和GitHub Repos
这是正确的方法吗?如果没有,我将感谢您在正确方向上的指导。预先谢谢你。