快递和Firebase-无法在重定向之前设置标头 [英] Express & Firebase - Failing to set header before redirect

查看:91
本文介绍了快递和Firebase-无法在重定向之前设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使Firebase身份验证在服务器上工作.

I am trying to make Firebase authentication work on the server.

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
//const expressSanitizer = require('express-sanitizer');
const app = express();

// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.

const validateFirebaseIdToken = (req, res, next) => {
   console.log('Check if request is authorized with Firebase ID token');

   if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
  !(req.cookies && req.cookies.__session)) {
       console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
    'Make sure you authorize your request by providing the following HTTP header:',
    'Authorization: Bearer <Firebase ID Token>',
    'or by passing a "__session" cookie.');
    res.redirect("/login");
    return;
   }

   let idToken;
   if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
   console.log('Found "Authorization" header');
     // Read the ID Token from the Authorization header.
     idToken = req.headers.authorization.split('Bearer ')[1];
   } else if(req.cookies) {
     console.log('Found "__session" cookie');
     // Read the ID Token from cookie.
     idToken = req.cookies.__session;
   } else {
     // No cookie
     res.redirect("/login");
     return;
   }

   admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
      console.log('ID Token correctly decoded', decodedIdToken);
      req.user = decodedIdToken;
      return next();
   }).catch((error) => {
      console.error('Error while verifying Firebase ID token:', error);
      res.redirect("/login");
   });
 };

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("/public"));
app.use(cors);
app.use(cookieParser);
//app.use(expressSanitizer());
//app.use(validateFirebaseIdToken);=
app.set("view engine", "ejs");

// This HTTPS endpoint can only be accessed by your Firebase Users.
// Requests need to be authorized by providing an `Authorization` HTTP header
// with value `Bearer <Firebase ID Token>`.
exports.app = functions.https.onRequest(app);



app.post("/login", (request, response) => {

   var idToken = request.body.token;

   console.log("REQUEST BODY = " + idToken);

   response.header("Authorization" , "Bearer " + idToken);

   return response.redirect("dashboard");
});

app.get("/dashboard", validateFirebaseIdToken, (request, response) => {
   response.redirect("/dashboard/new");
});

/login POST路由中,我按预期方式收到了idToken(并显示在日志中). 不过,响应似乎无法保存/维护预先设置的标头属性Authentication: Bearer <Firebase ID token> .

In the /login POST route, I am receiving the idToken as expected (and showed in the logs). It seems though, that the response is unable to preserve/maintain the header property Authentication: Bearer <Firebase ID token> set beforehand.

实际上,我通过获取日志中打印的idToken并将其设置在请求的标头中(例如Authorization: Bearer <idToken>),在Postman中将GET请求发送到了/dashboard,并且效果很好.

In fact, I sent a GET request in Postman to /dashboard by getting the idToken printed by the logs and setting it in the header of the request like Authorization: Bearer <idToken> and it worked perfectly.

此处表示,重定向实际上是新的HTTPS请求,因此不要保留响应中设置的标头.在这种情况下我该怎么办?

Here it says that redirects are in fact new HTTPS requests and therefore don't preserve the header set in the response. What should I do in this case?

推荐答案

您必须随个请求发送Authorization标头. HTTPS函数是无状态的.他们不记得任何先前的请求.因此,您不应该依赖重定向行为来保持状态.相反,客户端需要弄清楚下一步要去哪里,然后自己发出下一个请求.

You have to send the Authorization header with every request. HTTPS functions are stateless. They don't remember anything from a prior request. So, you shouldn't depend on redirect behavior to retain state. Instead, the client needs to figure out where to go next and make the next request itself.

这篇关于快递和Firebase-无法在重定向之前设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆