Javascript 如何在firebase函数中取消对一条路由的保护
我使用了这个代码示例,其中附加了一个代码片段:Javascript 如何在firebase函数中取消对一条路由的保护,javascript,node.js,firebase,express,firebase-authentication,Javascript,Node.js,Firebase,Express,Firebase Authentication,我使用了这个代码示例,其中附加了一个代码片段: const validateFirebaseIdToken = (req, res, next) => { cors(req, res, () => {}); // console.log("Check if request is authorized with Firebase ID token"); if ( (!req.headers.authorization || !req
const validateFirebaseIdToken = (req, res, next) => {
cors(req, res, () => {});
// 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.status(403).send("Unauthorized");
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.status(403).send("Unauthorized");
return;
}
我想通过授权令牌保护文件中的其他几个端点,但这一个路由不需要保护。此处显示的代码仅显示
validateFireBaisedToken
的定义,而不显示它的使用位置。在链接的示例中,您可以看到它正在应用于整个应用程序:
app.use(validateFirebaseIdToken);
如果您这样做,它将应用于所有的路由,这就是中间件的工作方式
如果希望此中间件仅应用于某些路由,则应将其作为参数传递给app.post()
,如的文档所示。您需要将中间件函数传递给app.post()
,以便它描述该路由要完成的所有处理
app.post("/routeYouWantProtected", validateFirebaseIdToken, (req, res) => { ... })
或者,您可以重写中间件,仅在提供令牌的情况下对其进行解码。如果您这样做,您可以检查处理程序函数内部是否存在,并决定如何处理该结果
app.post("/routeYouWantProtected", validateFirebaseIdToken, (req, res) => { ... })