Используя Firebase Auth, могу ли я также установить Session Cookies для GET-запросов? - PullRequest
0 голосов
/ 17 октября 2018

Это мой код на стороне клиента:

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, я могу назначить сеансовые куки.

Вот мой код на стороне сервера:

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.Пользователь, не прошедший проверку подлинности, не может отправлять запросы POST.Однако я надеялся аутентифицировать пользователей и обслуживать связанные с ними данные.Итак, как я могу использовать эти сеансовые куки-файлы для обслуживания маршрутов по GET-запросам?Прямо сейчас моя клиентская сторона не отправляет эти куки-файлы по запросам GET.

Я следовал этим документам Firebase и Репозитории GitHub

Будетэто будет правильный подход?Если нет, я буду признателен за ваше руководство в правильном направлении.Заранее спасибо.

...