更新到passport-jwt并获得未经授权的错误

时间:2018-04-14 19:41:40

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

我已从passport-jwt 1.2.1升级到pasport-jwt 4.0。我更新了护照代码以使用ExtractJwt.fromHeader,我认为它标记为'Authorizaton',您将在下面的Header Request代码中看到。

var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;

// load up the user model
var User = require('../models/user');
var config = require('../config/database'); // get db config file


module.exports = function(passport) {
  var opts = {}
  opts.jwtFromRequest = ExtractJwt.fromHeader('Authorization');
  opts.secretOrKey = 'secret';

  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
      User.findOne({id: jwt_payload.sub}, function(err, user) {
          if (err) {
              return done(err, false);
          }
          if (user) {
              return done(null, user);
          } else {
              return done(null, false);
          }
      });
  }));
};

我的标题请求如下所示,其中只包含一些测试代码。

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1YWQyNTc3MWQwZWM3YzQ2YmFhNjYzOTgiLCJsb2dpbiI6ImNuYWtlYSIsInBhc3N3b3JkIjoiJDJhJDEwJFAzVG1wNDU3ZmhHdHdnaTZseGRRSGVRUENmR1F0OWMvWHVtSDZCTEtUlVQbUEvLnZvRGp5IiwiZW1haWwiOiJjaHJpc0BjaHJpc25ha2VhLmNvbSIsImNvbmZpcm1hdGlvbljb2RlIjoiMjk3NTNiZDYtZTQyYi1kYjRkLWM4ODUtZDE5MzlmYjdkZWU4IiwiY29uZmlybV9leHBpcmUiOiyMDE4LTA0LTE1VDE5OjMzOjA1LjQ0OVoiLCJfX3YiOjAsImNvbmZpcm1lZCI6dHJ1ZX0.ow_5ZsqEeP_2oJxG7IuzZUJrsZa84CDMW3Nk4qXbgik
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:3000
Origin: http://localhost:8100
Pragma: no-cache
Referer: http://localhost:8100/
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1

出于某种原因,我收到了“未经授权”的回复。

这就是我从angularjs服务中拨打电话的方式:

  function useCredentials(token) {
    isAuthenticated = true;
    authToken = token;

    // Set the token as header for your requests!
    $http.defaults.headers.common.Authorization = authToken;
  }

我该如何解决这个问题?

因此看起来认证代码正常工作,实际上这个代码失败了:

var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database'); 
var passport  = require('passport');

require('../config/passport')(passport);

var User = require('../models/user');

router.route('/')

.get(passport.authenticate('jwt', { session: false}), function(req, res) {

  var token = getToken(req.headers);

  if (token) {

    var decoded = jwt.decode(token, config.secret);

    User.findOne({
      login: decoded.login
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
          return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
        } else {

          //CUSTOMIZE DATA TO RETURN ***
          var data = {
            id:user.id,
            login:user.login,
            email:user.email
          };

          res.json(data);
        }
    });

  } else {
    return res.status(403).send({success: false, msg: 'No token provided.'});
  }
});

getToken = function (headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
      return parted[1];
    } else {
      return null;
    }
  } else {
    return null;
  }
};

module.exports = router;

1 个答案:

答案 0 :(得分:1)

试试这个:

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();

这将创建一个新的提取器,在授权标题中查找JWT并使用方案' bearer'所以你的标题将是这样的Authorization: Bearer jk12h3j231231jkl12j

function useCredentials(token) {
    isAuthenticated = true;
    authToken = token;

    // Set the token as header for your requests!
    $http.defaults.headers.common.Authorization = `Bearer ${authToken}`;
}