I am facing issues with my Passport.js functions not authenticating users properly.
When I use the current form, it always returns "unauthorized" for all requests:
import passport from 'passport'
import passportJWT from 'passport-jwt'
import userModel from '../user/user.model'
import {Request, Response, NextFunction} from 'express'
export default class PassportController{
static async setup(app: express.Application){
const JWTStrategy = passportJWT.Strategy
const ExtractJwt = passportJWT.ExtractJwt
const config = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
issuer: 'DepoApp',
}
passport.use(userModel.createStrategy())
passport.use(new JWTStrategy(
config,
(payload, done) => {
userModel.findOne({_id: payload.id}, (err:any, user:any) => {
if(err) {
return done(err, false)
}
else if(user){
return done(null, user)
}
else{
return done(null, false)
}
})
}
))
}
static async auth(req: Request, res: Response, next: NextFunction){
await passport.authenticate('jwt', {session: false})(req, res, next)
}
}
Changing the auth
method as shown below causes it to authorize all users regardless of their token:
static async auth(req: Request, res: Response, next: NextFunction){
await passport.authenticate('jwt', {session: false})
next()
}
I suspect that the issue lies in the improper implementation of the middleware auth
. Please guide me on how to configure it correctly.
In my index.ts
file, I simply call PassportController.setup()
Note #1: Sessions are not being used
Note #2: The user model does not have a username field and uses _id as the default key. User model structure is as follows:
import mongoose from 'mongoose'
import { Schema } from 'mongoose'
import Permits from './permits.enum'
import passportLocalMongoose from 'passport-local-mongoose'
const userSchema = new Schema({
_id: {type: String},
first_name: {type: String, required: true},
last_name: {type: String, required: true},
phone: {type: String, required: true},
mail: {type: String, required: true, lowercase: true, trim: true, unique: true},
permits: [{type: String, enum: Permits, default: []}],
},
{
collection: 'users',
timestamps: true,
})
userSchema.plugin(passportLocalMongoose, {usernameField: '_id'})
const userModel = mongoose.model('User', userSchema)
export default userModel
I have experimented with different approaches to modify the auth
method as mentioned above. Additionally, when I inspect the contents of payload
within JWTStrategy()
, nothing is logged (it appears empty as if the function was never called).
A similar question suggested issues with routes, but in my case, everything seems to be in order.
Routes:
this.app.route('/api/depo')
.get(PassportController.auth, DepoController.getAll)
.post(PassportController.auth, DepoController.post)
this.app.route('/api/depo/:id')
.get(PassportController.auth, DepoController.getById)
.patch(PassportController.auth, DepoController.patchById)
.delete(PassportController.auth, DepoController.deleteById)
this.app.route('/api/no-gdpr/depo/')
.get(DepoController.getAllNoGDPR)
this.app.route('/api/no-gdpr/depo/:id')
.get(DepoController.getOneNoGDPR)