How to use the passport-jwt.Strategy function in passport-jwt

To help you get started, we’ve selected a few passport-jwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github peerism / peerai-api / middleware / auth.js View on Github external
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);
      })
github pietrzakadrian / bank / backend / src / middlewares / authHandler.middleware.ts View on Github external
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);
github tmeasday / create-graphql-server / test / output-app / server / authenticate.js View on Github external
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');
github raphaellima8 / typescript-api / server / auth.js View on Github external
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 }); }
    };
github stalniy / casl-express-example / src / modules / auth / jwt.js View on Github external
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));
}
github KevinNTH / express-jwt-mongoose-example / config / passport.js View on Github external
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);
      }
    });
  }));
};
github hmol / node-api-token-auth / src / utils / passportHelper.ts View on Github external
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);
				});
		});
	}
}
github tmeasday / create-graphql-server / skel / server / authenticate.js View on Github external
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');
github ExpressGateway / express-gateway / lib / actions / jwt.js View on Github external
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
github NielsDom / ecommerce-react / services / passport.js View on Github external
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);
		}
	});
}));