I have integrated passport for authenticating calls to my express API. The setup is fairly standard:
/* Passport Configuration */
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
secretOrKey: config.auth.passport.key,
}
passport.use(
'jwt',
new JWT.Strategy(jwtOptions, (payload, done) => {
console.log('Using JWT Strategy')
User.findOne({ email: payload.email }, (err, user) => {
if (err) {
return done(err, false)
}
if (user) {
done(null, user)
} else {
done(null, false)
}
})
}),
)
/* Middleware */
const checkToken = passport.authenticate('jwt', { session: false })
const logAuthInfo = (req, res, next) => {
console.log(req.headers)
console.log(req.user)
}
/* Routes */
app.use(passport.initialize())
app.use('/graphql', checkToken, logAuthInfo, graphqlHTTP(graphQLConfig))
// Other REST routes, including login
After a successful login, I receive a JWT which works when used in requests to /graphql
. However, an unauthenticated request without the token results in a 401 error. What I want to achieve is applying the checkToken
middleware to all requests, and assigning req.user
with either the authenticated user data or false
, leaving authorization handling for later.
Upon making a token-less request, I noticed that the 'Using JWT Strategy' log does not appear in the console, indicating that the middleware isn't even executed.
Any suggestions on how to tackle this issue?