Created
March 20, 2019 15:46
-
-
Save chrnx-dev/eb9818754533a71b8a31df9fb0e9762f to your computer and use it in GitHub Desktop.
Passport JWT Strategy Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import JWT from '@core/classes/JWT'; | |
import { JWT_AUDIENCE, JWT_HEADER, JWT_ISSUER, JWT_SECRET } from '@core/constants'; | |
import * as mongoose from 'mongoose'; | |
import { ExtractJwt, Strategy } from 'passport-jwt'; | |
export default async function jwt(passport) { | |
const User = mongoose.model('User'); | |
const options = { | |
audience: JWT_AUDIENCE, | |
ignoreExpiration: true, | |
issuer: JWT_ISSUER, | |
jwtFromRequest: ExtractJwt.fromHeader(JWT_HEADER), | |
passReqToCallback: true, | |
secretOrKey: JWT_SECRET | |
}; | |
const strategy = new Strategy(options, async (req, jwt, done) => { | |
try { | |
if (!await JWT.isValid(req.header(JWT_HEADER))) { | |
return done(new Error('Invalid Token'), null); | |
} | |
const user = await User.findById(jwt.sub).lean(true); | |
if (!user) { | |
done(new Error('User does not exists.'), null); | |
} | |
done(null, user); | |
} catch (e) { | |
done(e, null); | |
} | |
}); | |
passport.use(strategy); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment