How to use the passport-jwt.ExtractJwt 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 alqamabinsadiq / node-api-kit / server / verify.js View on Github external
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let User = require('../features/users/user.model');
let JwtStrategy = require('passport-jwt').Strategy;
let ExtractJwt = require('passport-jwt').ExtractJwt;
let jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
let FacebookTokenStrategy = require('passport-facebook-token');
let config = require('../config/config');
const Iron = require('iron');

// Returns the sign jwt
exports.getToken = (user, expiresIn) => {
  return jwt.sign(user, config.secretKey,
    { expiresIn: expiresIn || 3600 });
};

// Check whether the user has admin privileges or not.
exports.verifyAdmin = (req, res, next) => {
  console.log(req.user);
  if (req.user.admin) {
    next();
github tanem / express-bookshelf-realworld-example-app / lib / initializers / 06-passport-jwt.js View on Github external
'use strict';

const ExtractJwt = require('passport-jwt').ExtractJwt;
const JwtStrategy = require('passport-jwt').Strategy;
const passport = require('passport');
const config = require('../../config');

module.exports = () => {
  passport.use(
    new JwtStrategy(
      {
        secretOrKey: config.get('secret'),
        jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Token'),
      },
      ({id}, done) => {
        // The real user is fetched within the callback, but we need to pass
        // something truthy in the user slot here so that passport auth works
        // correctly (e.g. for the optional auth setup).
        done(null, {userId: id});
github alqamabinsadiq / node-api-kit / server / authenticate.js View on Github external
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../features/users/user.model');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
const FacebookTokenStrategy = require('passport-facebook-token');
let Q = require('q');
const Iron = require('iron');
const verify = require('./verify');
const config = require('../config/config');
// passport.use(new LocalStrategy(here we supply the verify function since we are using passport mongoose
// plugin so we can use authenticate method supplied by it ))
exports.local = passport.use(new LocalStrategy(User.authenticate()));

// This will take care of whatever is reqd for support for sessions in passport
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

/* 
Opts contains the information for JwtStrategy, 
github SaifRehman / ICP-Airways / icp-backend / login-microservice / dist / App.js View on Github external
constructor() {
        this.jwtOptions = {};
        this.ExtractJwt = passportJWT.ExtractJwt;
        this.JwtStrategy = passportJWT.ExtractJwt;
        this.jwtOptions.jwtFromRequest = this.ExtractJwt.fromAuthHeaderAsBearerToken();
        this.jwtOptions.secretOrKey = process.env.SECRET;
        this.connectionString = 'DATABASE=' + (process.env.DATABASE) + ';' +
            'HOSTNAME=' + process.env.HOSTNAME + ';' + 'UID=' + process.env.UID + ';' +
            'PWD=' + process.env.PASSWORD + ';' + 'PORT=' + process.env.PORT + ';' +
            'PROTOCOL=' + process.env.PROTOCOL + ';';
        console.log(this.connectionString);
        this.express = express();
        this.middleware();
        this.routes();
    }
    middleware() {
github SaifRehman / ICP-Airways / icp-backend / odm-microservice / src / App.ts View on Github external
import * as path from 'path';
import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import * as passwordhash from 'password-hash'
import * as passport from 'passport'
import * as jwt from 'jsonwebtoken'
import * as passportJWT from 'passport-jwt'
import * as Request from 'request'
import * as epimetheus from 'epimetheus'

class App {
  public jwtOptions: any = {};
  public ExtractJwt = passportJWT.ExtractJwt;
  public JwtStrategy = passportJWT.ExtractJwt;
  public express: express.Application;
  constructor() {
    this.jwtOptions.jwtFromRequest = this.ExtractJwt.fromAuthHeaderAsBearerToken();
    this.jwtOptions.secretOrKey = process.env.SECRET;
    this.express = express();
    epimetheus.instrument(this.express)
    this.middleware();
    this.routes();
  }
  private ensureToken(req, res, next) {
    const bearerHeader = req.headers["authorization"];
    if (typeof bearerHeader !== 'undefined') {
      const bearer = bearerHeader.split(" ");
      const bearerToken = bearer[1];
      req.token = bearerToken;
      next();
github mariocoski / express-typescript-react-redux-universal / api / build / auth / passport.js View on Github external
if (!user) {
                    return [2 /*return*/, done(null, false)];
                }
                userModel = user.get({ plain: true });
                return [4 /*yield*/, utils_1.comparePassword(password, userModel.password)];
            case 2:
                isMatch = _a.sent();
                if (isMatch) {
                    return [2 /*return*/, done(null, user)];
                }
                return [2 /*return*/, done(null, false)];
        }
    });
}); });
var jwtOptions = {
    jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: utils_1.env('JWT_SECRET'),
    session: false
};
var jwtLogin = new passport_jwt_1.Strategy(jwtOptions, function (payload, done) { return __awaiter(_this, void 0, void 0, function () {
    var user;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (!payload._id) {
                    return [2 /*return*/, done(new errors_2.BadRequestError(), false)];
                }
                return [4 /*yield*/, userRepo_1.findUserById(payload._id)];
            case 1:
                user = _a.sent();
                if (user) {
                    return [2 /*return*/, done(null, user)];
github notadd / next / packages / authentication / strategies / jwt.strategy.js View on Github external
constructor(service) {
        super({
            jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken(),
            passReqToCallback: true,
            secretOrKey: "secret",
        }, async (req, payload, next) => this.verify(req, payload, next));
        this.service = service;
        passport.use(this);
    }
    async verify(req, payload, done) {
github codyseibert / tab-tracker / server / src / passport.js View on Github external
const passport = require('passport')
const {User} = require('./models')

const JwtStrategy = require('passport-jwt').Strategy
const ExtractJwt = require('passport-jwt').ExtractJwt

const config = require('./config/config')

passport.use(
  new JwtStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: config.authentication.jwtSecret
  }, async function (jwtPayload, done) {
    try {
      const user = await User.findOne({
        where: {
          id: jwtPayload.id
        }
      })
      if (!user) {
        return done(new Error(), false)
github alice-si / monorepo / packages / donations-app / devServer / passport.js View on Github external
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const assert = require('assert');

const Utils = require('./service/utils');
const Config = require('../config');

function checkScope (scope, req) {
  assert(scope == 'donations_only' || scope == 'full_access');

  function epAllowed (req, allowedEndpoints) {
    return allowedEndpoints.reduce((acc, allowedEp) =>
      acc || req.path.startsWith('/api/' + allowedEp), false);
  }

  if (scope == 'donations_only') {
    let allowedEndpoints = [
      'checkDonationStatus',