NodeJS:Passport JWT(v4.0.0)无法通过POSTMAN Rest Client验证用户身份,始终返回未经授权的

时间:2018-10-29 08:52:03

标签: node.js express authentication jwt passport-jwt

我正在使用express js作为后端框架,目前正在使用Passport-JWT进行登录身份验证模块,

我想在专用路由上使用身份验证中间件。

我不想在每条路线上都写passport.authenticate('jwt', {session: false},相反,我想做一个函数并在每个请求中使用它,例如

router.get('/current',isAuthenticated,controllers.auth.user);

登录身份验证正常工作,但是在此之后,当我访问专用路由时,它始终会提供"Unauthorized."

我搜索了很多相同的问题,但是没有一个对我有用,所以我再次问这个问题

当用户成功登录后,以下令牌已存储在本地存储中。

enter image description here

当我尝试从邮递员休息客户端

  
      
  • 当我使用passport.authenticate('jwt', {session: false}时,它会给未经授权的人
  •   

enter image description here

  
      
  • 当我使用isAuthenticate时显示错误{name:'JsonWebTokenError',message:'invalid signature'}护照中间件
  •   

enter image description here

我正在使用此软件包版本:

"passport": "^0.4.0",

  "passport-jwt": "^4.0.0",

  "jsonwebtoken": "^8.3.0",

这是我的 helpers / passport.js

const options = {};
options.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
options.secretOrKey = 'qwer123poiuasdf234092482094';
module.exports = passport => {
  passport.use(
    new JwtStrategy(options, (jwt_payload, done) => {

      User.findById(jwt_payload._id)
        .then(user => {
          if (user) {
            return done(null, user);
          }
          return done(null, false);
        })
        .catch(err => {
          console.log(err);
          return done(err, false);
        });
    })
  );
};

这是我的 server.js

global.express = require('express');
global.app = express();

global.passport = require('passport');
global.jwt = require('jsonwebtoken');
global.JwtStrategy = require('passport-jwt').Strategy;
global.ExtractJwt = require('passport-jwt').ExtractJwt;

global.logger = require('morgan');
global.Validator = require('validator');

global.bcrypt = require('bcrypt-nodejs');
global.crypto = require('crypto');
global.bodyParser = require('body-parser');
global.cookieParser = require('cookie-parser');
global.requireTree = require('require-tree');
global.mongoose = require('mongoose');
global.autoIncrement=require('mongoose-auto-increment');
mongoose.Promise = Promise;
mongoose.set('useCreateIndex', true);
var mongooseOptions = {  useNewUrlParser: true }
global.Schema = mongoose.Schema;
autoIncrement.initialize(mongoose);

global.rootdir = __dirname;
global.ejs=require('ejs');
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')


global.configuration = requireTree(rootdir + '/configuration')
global.helpers = requireTree(rootdir + '/helpers')
require(rootdir+'/helpers/passport')(passport)
global.validation = requireTree(rootdir + '/validation')

mongoose.connect(configuration.config.MONGODB_URI, mongooseOptions, function(err) {
    if (err) {
        console.error('System could not connect to mongo server.')
        console.log(err)
        process.exit()
    } else {
        console.log('System connected to mongo server.')
    }
});


app.use(logger('dev'));  
app.use(passport.initialize())

app.use(express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
    extended: true,
    limit: '50mb',
    parameterLimit: 100000
}))
app.use(bodyParser.json({
    limit: '50mb',
    parameterLimit: 100000
}))


app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Request-Headers", "*");
    res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials", "true");
    next();
});


 // this function i want to use as middleware on private routes

global.isAuthenticated=function(req, res, next) {

     if (req.headers.authorization) {
        passport.authenticate('jwt', {session: false}, function (err, user, info) {
            console.log('errr==',err);
            console.log('user==',user);
            console.log('info==',info);

            if ((!err || !info) && user) {
                req.user = user;
                return next();
            }
            res.status(401).json({status:'error',isAuthenticated: false, message: "Unauthorized"});
        })(req, res, next);
    } else {

        res.status(401).json({status:'error',isAuthenticated: false, message: "Unauthorized"});
    } 
} 

app.use('/api/auth',routes.api.auth);

var port = process.env.PORT || 8888;
app.listen(port);

这是 routes / api / auth.js

const router=express.Router();

router.get('/current',isAuthenticated,(req,res)=>{
    res.json({
        user:req.user
      });
});

module.exports =router

请帮助我解决此问题

1 个答案:

答案 0 :(得分:0)

首先,“无法获得任何响应”错误不是由于身份验证错误造成的,这可能是因为服务器已关闭或API路由不存在。

第二,确保您使用的令牌已配置为具有Bearer,否则仅发送令牌(不带Bearer)。

  

我认为在您的情况下,您没有发送正确的令牌(请尝试删除   客户)。