节点js Passport授权 - JWT策略不会被调用

时间:2017-08-01 19:34:33

标签: javascript node.js jwt passport.js

我正在尝试构建一个meanauth应用程序,我使用jws令牌来授权用户。

这是我的route / users.js文件

const express = require('express');
const router = express.Router();
const passport = require('passport');
const config = require('../config/database');
const jwt = require('jsonwebtoken');
var Log = require('log')
  , log = new Log('info');

const User = require('../model/users');
//const ap = express();

//Register router
router.post('/register',(req,res,next)=>{
  log.info('entering register');
  let newUser = new User({
    name:req.body.name,
    email:req.body.email,
    username:req.body.username,
    password:req.body.password
  });
  User.addUser(newUser,(err,user)=>{
    log.info("inside add user");
    if(err){
      log.error('error while registaring ' + err);
      res.json({success:false,msg:'failed to register user'});
    }
    else {
      res.json({sucess:true,msg:'user registered succefully'});
    }
  })
});
router.post('/authenticate',(req,res,next)=>{
  const username = req.body.username;
  const password = req.body.password;
  User.getUserByUsername(username,(err,user)=>{
  if(err)
  throw err;
  if(!user)
  {
    return res.json({success:false,msg:'user not found'});
  }
  User.comparePassword(password,user.password,(err,isMatch) => {
    if(err) throw err;
    if(isMatch){
      const token = jwt.sign(user,config.secret,{
        expiresIn: 604800 // 1 week
      });
      res.json({
        success:true,
        token:'JWT'+token,
        id:user._id,
        name:user.name,
        username:user.username,
        email:user.email
      });
    }
    else
      {
        return res.json({success:false,msg:'wrong password'});
      }
  });


});
});
router.get('/profile',passport.authenticate('jwt',{session:false}),(req,res,next)=>{
  log.info('inside profile');
  res.json({user: req.user});
});
module.exports=router;

这是passport.js

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

module.exports = function(passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts,(jwt_payload,done)=>{
    console.log("inside passport");
    console.log(jwt_payload);
    User.getUserById(jwt_payload._doc._id,(err,user)=>{
      if(err)
      {
        return done(err,false);
      }
      if(user){
        return done(null,user);
      }
      else {
        return done(null,false);
      }
    })
  }));
}

当我使用jwt授权令牌向/ profile发出请求时,我收到未经授权的消息,我试图在/ profile路由和passport.js中控制日志,但我没有得到任何东西,这里有什么问题?

0 个答案:

没有答案