护照JWT JSON Web Token身份验证错误

3

这是我第一次实现使用passport和JWT进行身份验证。我的问题是:当我在header中发送一个已过期的token时,会收到“未经授权”的消息。我的代码如下:

在routes.js中:

app.route('/people/:id')
        // .all(function(req, res, next) {
        //     app.auth.authenticate(req, res, next);
        // })
        // .all(app.auth.authenticate)
        .all(app.auth.authenticate())
        .get(controller.getPeopleById)
        .delete(controller.deletePeople);

注释部分是我尝试过的

在auth.js文件中:

var passport = require("passport");
var passportJWT = require("passport-jwt");
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;

module.exports = function(app) {
    const options = {
        secretOrKey: app.config.config.jwtSecret,
        jwtFromRequest: ExtractJwt.fromAuthHeader()
    };

    var strategy = new Strategy(options, function(payload, done) {
        console.log("payload: " + JSON.stringify(payload));
    });

    passport.use(strategy);

    return {
        initialize : function() {
            return passport.initialize();
        },

        authenticate : function() {
            return passport.authenticate('jwt', app.config.config.jwtSession);
            // return passport.authenticate('jwt', app.config.config.jwtSession, function(error, done, info) {                    
            //     if (error) {
            //         console.log("error: " + error);
            //     }

            //     if (done) {
            //         console.log("done: " + JSON.stringify(done));
            //     }

            //     if (info) {
            //         console.log("info: " + info);
            //     }
            // });
            // }
        }
    }
};

在middlewares.js文件中:

var bodyParser = require("body-parser");
var config = require("./config/config")();

module.exports = function(app) {
    app.set("port", config.port || 3000);

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(app.auth.initialize());
};

我想做的就是捕获身份验证中发生的错误以自定义消息,例如:“令牌已过期,请重新登录”,但实际上它没有进入策略的验证方法。有人经历过这种情况吗?感激不尽。
1个回答

4

Passport总是抛出AuthenticationError。

要获取实际的错误,您必须向passport.authenticate方法提供回调函数。

例如:

app.get('/protected', function(req, res, next) {
        passport.authenticate('local', function(err, user, failuresOrInfo, status) {

        // failuresOrInfo has the cause.

          if (err) { return next(err) }
         if (!user) { return res.redirect('/signin') }
         res.redirect('/account');
        })(req, res, next);
      });

以下是passport代码片段:

function allFailed() {
      if (callback) {
        if (!multi) {
          return callback(null, false, failures[0].challenge, failures[0].status);
        } else {
          var challenges = failures.map(function(f) { return f.challenge; });
          var statuses = failures.map(function(f) { return f.status; });
          return callback(null, false, challenges, statuses);
        }
      }

...

请看,如果有回调函数(callback)存在,passport会将结果传递给回调函数,您需要处理其余部分。
希望我的回答清晰,并能为您提供帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接