Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
req.user = user;
next();
})
}
const jwtOptions = {
// Authorization: Bearer in request headers
jwtFromRequest: PassportJwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: JWT_SECRET,
// Algorithms used to sign in
algorithms: [JWT_ALGORITHM]
}
// Passport JWT Strategy triggered by validateJWTWithPassportJWT
// https://www.npmjs.com/package/passport-jwt
passport.use(new PassportJwt.Strategy(jwtOptions,
// Post-Verified token - https://www.npmjs.com/package/passport-jwt
(jwtPayload, done) => {
console.log('PassportJwt Strategy being processed');
// Find user in MongoDB using the `id` in the JWT
User.findById(jwtPayload.sub)
// User.findById(jwtPayload._doc._id)
.then((user) => {
if (user) {
done(null, user);
} else {
done(null, false);
}
})
.catch((error) => {
done(error, false);
})
getJWTStrategy(): Strategy {
return new JWTStrategy(this.jwtOptions, async (jwt_payload, next) => {
const userService = new UserService();
try {
const user = await userService.getById(jwt_payload.id);
// if user not found for this id
if (!user) {
return next(null, false);
}
// authentication passed
return next(undefined, {
id: user.id
});
} catch (err) {
return next(null, false);
import jwt from 'jwt-simple';
import { ObjectId } from 'mongodb';
import nodeify from 'nodeify';
import bcrypt from 'bcrypt';
const KEY = 'test-key';
async function userFromPayload(request, jwtPayload) {
if (!jwtPayload.userId) {
throw new Error('No userId in JWT');
}
return await request.context.User.findOneById(ObjectId(jwtPayload.userId));
}
passport.use(new Strategy({
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: KEY,
passReqToCallback: true,
}, (request, jwtPayload, done) => {
nodeify(userFromPayload(request, jwtPayload), done);
}));
export default function addPassport(app) {
app.use(passport.initialize());
app.post('/login', async (req, res, next) => {
try {
const { email, password } = req.body;
if (!email || !password) {
throw new Error('Username or password not set on request');
function AuthConfig() {
var UserService = new service_1.User();
var opts = {
secretOrKey: config.secret,
jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeader()
};
passport.use(new passport_jwt_1.Strategy(opts, function (jwtPayload, done) {
UserService.getById(jwtPayload.id)
.then(function (user) {
if (user) {
return done(null, {
id: user.id,
email: user.email
});
}
return done(null, false);
})
.catch(function (error) { return done(error, null); });
}));
return {
initialize: function () { return passport.initialize(); },
authenticate: function () { return passport.authenticate('jwt', { session: false }); }
};
function configurePassport(passport, app) {
const options = {
issuer: app.get('jwt.issuer'),
audience: app.get('jwt.audience')
};
BLANK_JWT = BLANK_JWT || generateBlankJwt(app.get('jwt.secret'), {
issuer: app.get('jwt.issuer'),
audience: app.get('jwt.audience')
});
passport.use(new Strategy({
...options,
secretOrKey: app.get('jwt.secret'),
jwtFromRequest: (req) => req.headers.authorization || BLANK_JWT,
}, findUser));
}
module.exports = function(passport) {
let opts = {
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: config.auth.secret
};
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.findOne({
id: jwt_payload.id
}, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
getPassportStrategy(): Strategy {
const params = {
secretOrKey: this.jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeader(),
passReqToCallback: true
};
return new Strategy(params, (req: any, payload: any, done: any) => {
Repository.get(payload.userid)
.then((user: user) => {
if(user === null) {
return done(null, false, { message: "The user in the token was not found" });
}
return done(null, { _id: user.id, username: user.username });
})
.catch((err: any) => {
return done(err);
});
});
}
}
import jwt from 'jwt-simple';
import { ObjectId } from 'mongodb';
import nodeify from 'nodeify';
import bcrypt from 'bcrypt';
const KEY = '~key~';
async function userFromPayload(request, jwtPayload) {
if (!jwtPayload.userId) {
throw new Error('No userId in JWT');
}
return await request.context.User.findOneById(ObjectId(jwtPayload.userId));
}
passport.use(new Strategy({
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: KEY,
passReqToCallback: true,
}, (request, jwtPayload, done) => {
nodeify(userFromPayload(request, jwtPayload), done);
}));
export default function addPassport(app) {
app.use(passport.initialize());
app.post('/login', async (req, res, next) => {
try {
const { email, password } = req.body;
if (!email || !password) {
throw new Error('Username or password not set on request');
function createJwtMiddleware (params) {
let jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeader(),
issuer: params.issuer,
audience: params.audience,
secretOrKey: params.key,
algorithms: params.algorithms
};
passport.use(new JwtStrategy(jwtOptions, (jwt, done) => {
done(null, jwt);
}));
return function jwtMiddleware (req, res, next) {
logger.debug('authenticating with JWT token');
passport.authenticate('jwt', (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
logger.debug(`authentication failed: ${info.message}`);
res.status(401).send({
error: {
name: 'Unauthorized',
message: info.message,
status: 401,
statusCode: 401
if(err){return done(err);}
if(!isMatch){return done(null, false);}
return done(null, user);
})
});
}));
//Setup options foor JWT Strategy
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: config.secret
};
//Create JWT Strategy
passport.use(new JwtStrategy(jwtOptions, function(payload, done){
//See if the user ID in the payload exists in our database
//If it does, call 'done' with that user
//otherwise, call done without a user object
User.findById(payload.sub, function(err, user){
//second argument is user object if we found one
if(err) {return done(err, false);}
if(user){
done(null, user);
}else{
done(null, false);
}
});
}));