如何使用passport.js和express实现条件身份验证



我想对我的API路由使用基本身份验证,但也允许用户通过本地身份验证策略访问浏览器中的API。我的中间件是这样的:

router.get("/Login", (req: Request, res: Response, next: NextFunction) => {
let test = req.flash("loginMessage");
res.render("Login", { message: test });
});
// Local authentication for user login
router.post(
"/Login",
passport.authenticate("local-login", {
failureRedirect: config.urlExtension + "/Login", // redirect back to the signup page if there is an error
failureFlash: true, // allow flash messages
})
);
// Basic authentication for API routes
router.all("/api/*", passport.authenticate("basic", { session: false }));
router.all("*", connectensurelogin.ensureLoggedIn(`${config.urlExtension}/Login`))

因此,对于API身份验证路由,如果已经通过登录实现了本地身份验证,我希望绕过基本身份验证。

我发现您可以从外部路由内部返回对身份验证路由的调用,条件如下:

// Basic authentication for API routes
router.all("/api/*", (req, res, next) =>
req.isAuthenticated()
? next()
: passport.authenticate("basic", { session: false })(req, res, next),
);

最新更新