Meaning, in my application, I want to check if a customId is present in the client request. If yes, I will proceed authentication using that with my custom logic. If customId is not present, I want to use passport-jwt authentication.
passport registers its initialize method at server startup itself. My specific question is how do I use passport.authenticate only if customId is not present.
Any help is much appreciated.
Yeah you can, it's all just middleware! Here's an example of how you would do it, I've not run this code so it may not build but it shows how to do what you're after.
const express = require('express');
const passport = require('passport');
const passportJWT = require('passport-jwt');
// My express application where I setup routers, middleware etc
const app = express();
// Initialise passport
app.use(passport.initialize());
// Setup my passport JWT strategy, this just setups the strategy it doesn't mount any middleware
passport.use(new passportJWT.Strategy({
secretOrKey: '',
issuer: '',
audience: '',
}, (req, payload, done) => {
doSomeFancyAuthThingy(payload, (err, user) => {
done(err, user);
});
}));
// Now create some middleware for the authentication
app.use((req, res, next) => {
// Look to see if the request body has a customerId, in reality
// you probably want to check this on some sort of cookie or something
if (req.body.customerId) {
// We have a customerId so just let them through!
next();
} else {
// No customerId so lets run the passport JWT strategy
passport.authenticate('jwt', (err, user, info) => {
if (err) {
// The JWT failed to validate for some reason
return next(err);
}
// The JWT strategy validated just fine and returned a user, set that
// on req.user and let the user through!
req.user = user;
next();
});
}
});
As you can see the main thing you're looking for is where we create the middleware. Here we just create our own middleware and run a check (the if statement), if it fails then we run passport.authenticate which triggers the strategy we created on the passport.use
block.
That will allow you to conditionally do any sort of authentication with Passport!