Reputation: 1556
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
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