wizzfizz94
wizzfizz94

Reputation: 1556

How to achieve conditional authentication with passport.js and express?

I would like to use basic authentication for my API routes but also allow users to access the API in the browser through the local authentication strategy. My middle-ware looks like this:

        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`))

So for the API authentication route I'd like to bypass basic authentication if local authentication has already been achieved by login.

Upvotes: 0

Views: 603

Answers (1)

wizzfizz94
wizzfizz94

Reputation: 1556

I found that you can return a call to the authentication route from inside a outer route with this conditional like so:

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

Upvotes: 2

Related Questions