How to use the passport-jwt.ExtractJwt.fromAuthHeader 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 solidgear / collaborative-newsletter / backend / server.js View on Github external
}))

    passport.serializeUser(function (user, done) {
        done(null, user);
    })

    passport.deserializeUser(function (user, done) {
        done(null, user);
    })

    if (config.JWT_STRATEGY) {
        var JwtStrategy = require('passport-jwt').Strategy;
        var ExtractJwt = require('passport-jwt').ExtractJwt;
        var opts = {};
        // Setup JWT options
        opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
        opts.secretOrKey = config.secret;

        passport.use(new JwtStrategy(opts, function (jwtPayload, done) {
            //If the token has expiration, raise unauthorized
            var expiration = moment(jwtPayload.exp * 1000);
            if(expiration.utc() < moment().utc()) {
                return done(null, false);
            }
            var user = jwtPayload;
            done(null, user);
        }))
    }
}
github tmeasday / create-graphql-server / test / output-app / server / authenticate.js View on Github external
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 dilagurung / node-sequelize-jwt-mysql / app / services / passportStrategy.js View on Github external
function hookJWTStrategy(passport)
{
    var options = {};

    options.secretOrKey = config.keys.secret;
    options.jwtFromRequest = ExtractJwt.fromAuthHeader();
    options.ignoreExpiration = false;

    passport.use(new JWTStrategy(options, function(JWTPayload, callback)
    {
console.log(JWTPayload,  'hi ')
        User.findOne({ where: { id: JWTPayload.id } })
            .then(function(user)
            {
                console.log('edddd');
                if(!user) {
                    callback(null, false);
                    return;
                }

                callback(null, user);
            }).catch(function (error) {
github TreeGateway / tree-gateway / src / service / redis / users.ts View on Github external
getAuthMiddleware(): express.RequestHandler {
        const opts: any = {
            jwtFromRequest: ExtractJwt.fromAuthHeader(),
            secretOrKey: this.config.gateway.admin.userService.jwtSecret
        };
        const strategy = new Strategy(opts, function(jwtPayload, done) {
            return done(null, jwtPayload);
        });
        auth.use('_tree_gateway_admin_', strategy);

        return auth.authenticate('_tree_gateway_admin_', { session: false, failWithError: true });
    }
}
github lhenriquegomescamilo / template-server-nodejs / server / auth-config.ts View on Github external
constructor() {
        this._userService = new UserService();
        this._options = {
            secretOrKey: config.secret,
            jwtFromRequest: ExtractJwt.fromAuthHeader()
        };
        
        this._configStrategyPassport(passport);
    }
github TreeGateway / tree-gateway / src / lib / service / users.ts View on Github external
getAuthMiddleware(): express.RequestHandler {
        const opts: any = {
            jwtFromRequest: ExtractJwt.fromAuthHeader(),
            secretOrKey: this.jwtSecretOrKey
        }
        let strategy =  new Strategy(opts, function(jwt_payload, done) {
            return done(null,jwt_payload);
        });
        auth.use("_tree_gateway_admin_", strategy);

        return auth.authenticate("_tree_gateway_admin_", { session: false, failWithError: true });
    }        
}
github TreeGateway / tree-gateway / src / lib / authentication / strategies / jwt.ts View on Github external
switch(extractor) {
        case 'header': return ExtractJwt.fromHeader(param);
        case 'queryParam': return ExtractJwt.fromUrlQueryParameter(param);
        case 'authHeader': return ExtractJwt.fromAuthHeaderWithScheme(param);
        case 'bodyField': return ExtractJwt.fromBodyField(param);
        case 'cookie': return (req)=>{
            let token = null;
            if (req && req.cookies)
            {
                token = req.cookies[param];
            }
            return token;
        };            
    }

    return ExtractJwt.fromAuthHeader();
}
github raphaellima8 / typescript-api / server / auth.ts View on Github external
export default function AuthConfig () {
  const UserService = new User();
  let opts = {
    secretOrKey: config.secret,
    jwtFromRequest: ExtractJwt.fromAuthHeader()
  };

  passport.use(new Strategy(opts, (jwtPayload, done) => {
    UserService.getById(jwtPayload.id)
      .then(user => {
        if(user) {
          return done(null, {
            id: user.id,
            email: user.email
          });
        }
        return done(null, false);
      })
      .catch(error => done(error, null));
  }));
github nathanni / TinyURL / app / config / passport.js View on Github external
module.exports = function (passport) {
    var opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function (jwt_payload, done) {

        //如果token被篡改, 即 part 1 + part2 不能hash出part3, 直接返回false, 底下的代码都不会执行
        UserModel.findOne({username: jwt_payload.username}, function (err, user) {
            if (err) {
                return done(err, false);
            }
            if (user && user.password === jwt_payload.password) {
                done(null, true);
            } else {
                done(null, false);
            }
        });
    }));
};