Node.js JWT策略总是返回未经授权的

Node.js JWT策略总是返回未经授权的,node.js,passport.js,jwt,Node.js,Passport.js,Jwt,我一直在尝试使用JWT和passport向我的应用程序添加授权。本地策略似乎没有任何问题,但JWT策略似乎不起作用 我的Passport.js文件 import passport from 'passport'; import User from '../models/regusers.model'; import config from '../config'; import jwtstrategy from 'passport-jwt'; import extractjwt from 'pa

我一直在尝试使用JWT和passport向我的应用程序添加授权。本地策略似乎没有任何问题,但JWT策略似乎不起作用

我的Passport.js文件

import passport from 'passport';
import User from '../models/regusers.model';
import config from '../config';
import jwtstrategy from 'passport-jwt';
import extractjwt from 'passport-jwt';
import LocalStrategy from 'passport-local';

const JwtStrategy = jwtstrategy.Strategy;
const ExtractJwt = extractjwt.ExtractJwt;

const localOption = {usernameField:'email'};

// create local Strategy
const localLogin = new LocalStrategy(localOption,(email,password,done)=>{
    //verify this username and password, call done true if true or false
    User.findOne({email:email},(err,user)=>{
       if(err){ return done(err);}
       if(!user){ return done(null,false);}

       // compare Password - is 'password' equal to user.password
       user.comparePassword(password,function(err,isMatch){
          if(err){ return done(err); }
          if(!isMatch) { return done(null,false); }

          return done(null,user);
       });
    });
});

// setup options for JWT Strategy
const jwtOptions = {
  jwtFromRequest:ExtractJwt.fromHeader('Authorization'),
  secretOrKey:config.secret
};

// Create JWT Strategy
const jwtLogin = new JwtStrategy(jwtOptions,function(payload,done){
   // see if user id in payload exists in our db
   //if it does, call done with that other
   //otherwise, call done without a user obejct
   User.findById(payload.sub,(err,user)=>{
      if(err){ return done(err,false); }

      if(user){
        done(null,user);
      }else{
        done(null,false);
      }

   });
});

passport.use(jwtLogin);
passport.use(localLogin);
import User from '../models/regusers.model';
import jwt from 'jwt-simple';
import config from '../config';
import bcrypt from 'bcrypt-nodejs';

let tokenForUser = (user) =>{
    const timpestamp = new Date().getTime();
    return jwt.encode({sub:user.id,iat:timpestamp},config.secret);
}


let login = (req,res,next) => {
      //User has already had their email and password auth'd
      //We just need to give them a token
      res.send({token:tokenForUser(req.user),unu:req.user.uname});
}

let signup = (req,res,next) => {

    const fname = req.body.fname;
    const lname = req.body.lname;
    const uname = req.body.uname;
    const email = req.body.email;
    const password =req.body.password;

    if(!email || !password){
       return res.status(422).send({error:'You must provide email and password'});
    }

    // See if a user with the given email exists
    User.findOne({email: email },(err,user)=>{
        if(err){
          return next(err);
        }
        //If a user with email does exists, return an erorr
        if(user){
          return res.status(422).send({error:'Email is in use'});
        }
        //if user with email does not exists,create and save user
        const newuser = new User({
          fname:fname,
          lname:lname,
          uname:uname,
          email:email,
          password:password
        });


        newuser.save((err)=>{
            if(err){ return next(err);}
            res.json({token:tokenForUser(newuser)});
            // res.json({success:'true'});
        });


    });
}

module.exports.signup = signup;
module.exports.login = login;
Myauthentication.js文件

import passport from 'passport';
import User from '../models/regusers.model';
import config from '../config';
import jwtstrategy from 'passport-jwt';
import extractjwt from 'passport-jwt';
import LocalStrategy from 'passport-local';

const JwtStrategy = jwtstrategy.Strategy;
const ExtractJwt = extractjwt.ExtractJwt;

const localOption = {usernameField:'email'};

// create local Strategy
const localLogin = new LocalStrategy(localOption,(email,password,done)=>{
    //verify this username and password, call done true if true or false
    User.findOne({email:email},(err,user)=>{
       if(err){ return done(err);}
       if(!user){ return done(null,false);}

       // compare Password - is 'password' equal to user.password
       user.comparePassword(password,function(err,isMatch){
          if(err){ return done(err); }
          if(!isMatch) { return done(null,false); }

          return done(null,user);
       });
    });
});

// setup options for JWT Strategy
const jwtOptions = {
  jwtFromRequest:ExtractJwt.fromHeader('Authorization'),
  secretOrKey:config.secret
};

// Create JWT Strategy
const jwtLogin = new JwtStrategy(jwtOptions,function(payload,done){
   // see if user id in payload exists in our db
   //if it does, call done with that other
   //otherwise, call done without a user obejct
   User.findById(payload.sub,(err,user)=>{
      if(err){ return done(err,false); }

      if(user){
        done(null,user);
      }else{
        done(null,false);
      }

   });
});

passport.use(jwtLogin);
passport.use(localLogin);
import User from '../models/regusers.model';
import jwt from 'jwt-simple';
import config from '../config';
import bcrypt from 'bcrypt-nodejs';

let tokenForUser = (user) =>{
    const timpestamp = new Date().getTime();
    return jwt.encode({sub:user.id,iat:timpestamp},config.secret);
}


let login = (req,res,next) => {
      //User has already had their email and password auth'd
      //We just need to give them a token
      res.send({token:tokenForUser(req.user),unu:req.user.uname});
}

let signup = (req,res,next) => {

    const fname = req.body.fname;
    const lname = req.body.lname;
    const uname = req.body.uname;
    const email = req.body.email;
    const password =req.body.password;

    if(!email || !password){
       return res.status(422).send({error:'You must provide email and password'});
    }

    // See if a user with the given email exists
    User.findOne({email: email },(err,user)=>{
        if(err){
          return next(err);
        }
        //If a user with email does exists, return an erorr
        if(user){
          return res.status(422).send({error:'Email is in use'});
        }
        //if user with email does not exists,create and save user
        const newuser = new User({
          fname:fname,
          lname:lname,
          uname:uname,
          email:email,
          password:password
        });


        newuser.save((err)=>{
            if(err){ return next(err);}
            res.json({token:tokenForUser(newuser)});
            // res.json({success:'true'});
        });


    });
}

module.exports.signup = signup;
module.exports.login = login;
我使用身份验证中间件的路由

import Authentication from '../auth/auth';
import passportService from '../services/passport';
import passport from 'passport';


const requireAuth = passport.authenticate('jwt',{session:false});
const requireLogin = passport.authenticate('local',{session:false});

const user = (app) => {

    app.get('/user',requireAuth,function (req,res){
        res.json({hi:'there'});
    });

    app.post('/login',requireLogin,Authentication.login);

    app.post('/signup',Authentication.signup);
}

export default user;

当我向用户路由发出get请求时,我将其作为未经授权获取的任何原因。

尝试更改:passport.use(jwtLogin);passport.use(localLogin);对此:passport.use('jwt',jwtLogin);passport.use('local',localLogin)@TRomesh我也遇到了同样的问题,你的问题解决了吗?@Adityajan不,我无法解决这个问题issue@TRomesh你是否已经缩小了你的程序的范围,直到它在哪里工作,你能告诉我你没有得到回应的具体行吗?