关于你的问题为什么passport.authenticate
在每个请求上调用,这是因为您将其定义为中间件,可能在任何路由逻辑发生之前。
如果您有私人and您的应用程序上的公共部分,您可以执行类似的操作:
// Define a specific that will handle authentication logic
app.get("/auth", passport.authenticate('facebook-token',function(){...});
// Public sections which do not require authentication
app.get("/public1",...);
app.post("/public2",...);
// Private sections which do require authentication
app.get("/private1", function(req,res,next){
if (req.isAuthenticated()){ // Check if user is authenticated
// do things...
}else{ // Wow, this guy is not authenticated. Kick him out of here !
res.redirect("/auth");
}
});
现在,如果您有多个私有部分,您可能会发现为每个私有部分执行相同的操作有点繁琐。
您可以定义一个自定义函数来检查用户是否经过身份验证,如果经过身份验证则允许请求继续进行。
就像是
function isThisGuyAuthenticated(req,res,next){
if (req.isAuthenticated()){
return next(); // Ok this guy is clean, please go on !
}else{
res.redirect("/auth"); // This guy is shady, please authenticate !
}
}
并像这样使用它:
app.get("/private1",isThisGuyAuthenticated, doCrazySecretStuff); // doCrazySecretStuff will not be called if the user is not authenticated
app.get("/private2", isThisGuyAuthenticated, getCocaColaRecipe);
app.get("/private3", isThisGuyAuthenticated, flyToMars);
app.get("/public", showInfo); // showInfo will be called whether the user is authenticated or not
现在,如果您的应用程序只有私有部分,您可以避免重复调用isThisGuyAuthenticated
通过将其定义为中间件(但不是通过定义passport.authenticate
本身作为中间件!);
// Endpoint that will be hit is the user is redirected to /auth
// BEWARE it needs to be above the middleware, otherwise you'll end up with an infinite redirection loop
app.get("/auth", passport.authenticate('facebook-token',function(){...});
// Middleware that will be called on every request
app.use(isThisGuyAuthenticated);
// You app's endpoints
app.get("/private1", doCrazySecretStuff); // doCrazySecretStuff will not be called if the user is not authenticated
app.get("/private2", getCocaColaRecipe);
app.get("/private3", flyToMars);
明白了吗 ?
EDIT:我错误地将中间件放在“/auth”端点之前。确保将其放置在之后