【问题标题】:How to achieve conditional authentication with passport.js and express?如何用passport.js和express实现条件认证?
【发布时间】:2020-12-04 10:48:54
【问题描述】:

我想对我的 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 身份验证路由,如果本地身份验证已经通过登录实现,我想绕过基本身份验证。

【问题讨论】:

    标签: node.js express authentication passport.js basic-authentication


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 2020-03-23
      • 2020-07-04
      • 2015-11-01
      • 2019-11-09
      • 1970-01-01
      相关资源
      最近更新 更多