使用 JWT 进行护照身份验证:如何将护照的默认未经授权响应更改为我的自定义响应?

Posted

技术标签:

【中文标题】使用 JWT 进行护照身份验证:如何将护照的默认未经授权响应更改为我的自定义响应?【英文标题】:Passport authentication with JWT: How can I change passport's default unauthorized response to my custom response? 【发布时间】:2019-05-30 20:08:26 【问题描述】:

我用passport 创建了一个Node 项目。当我没有将令牌作为标题时,它返回Unauthorized。如何将此消息更改为漂亮的Sorry invalid credentials

每次无法提供令牌时,我都会收到未经授权的响应。我想把它改成漂亮的消息。

passport.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');

var User        = require('../models/user'); // get the mongoose model

const keys = require('../config/keys');

const opts = ;

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

module.exports = passport => 
    passport.use(
        new JwtStrategy(opts, (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))
        )
    );
;

用户路由.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');
const setting=require("../validation/settings");


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


// *** GET *** /api/users/all *** Retrieve all users' basic details ***
router.get("/", passport.authenticate('jwt', session: false), function (req, res)

    var token = getToken(req.headers);
  console.log('the token: ' + token);

    User.find()
    .select('fname lname email avatar contact_no role')
    .where('is_deleted').equals('false')
    .exec()
    .then(docs => 
        return res.send(setting.status("User details retrieval successfully",false, "User details retrieval successfully", docs))
        //res.status(200).json(setting.status(validation.SHOW,true,"User details retrieval successfully.",docs))
    .catch(err => 
        return res.send(setting.status("Error in retrieving user details",false, "Error may token", err))
    );
    );
);


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;

如何将unauthorized 消息更改为漂亮(“您无法获取详细信息,”)

【问题讨论】:

检查documentation 的护照。您可以使用 Flash 消息来实现这一点。我 我试过但没用。我认为它不属于我的 passport.js 【参考方案1】:

根据Passport的官方文档,您可以使用custom callback函数来处理授权失败的情况并覆盖默认消息。

如果您正在开发 REST API,然后您希望发送漂亮的 JSON 响应,如下所示:


    "error": 
        "name": "JsonWebTokenError",
        "message": "invalid signature"
    ,
    "message": "You cannot get the details. You are not authorized to access this protected resource",
    "statusCode": 401,
    "data": [],
    "success": false

我使用Passport JWT 身份验证来保护我的一些路由,并应用了authMiddleware,如下所示:

app/middlewares/authMiddleware.js

const express = require('express');
const router = express.Router();
const passport = require('passport');
const _ = require('lodash');

router.all('*', function (req, res, next) 
  passport.authenticate('jwt',  session: false , function(err, user, info) 

    // If authentication failed, `user` will be set to false. If an exception occurred, `err` will be set.
    if (err || !user || _.isEmpty(user)) 
      // PASS THE ERROR OBJECT TO THE NEXT ROUTE i.e THE APP'S COMMON ERROR HANDLING MIDDLEWARE
      return next(info);
     else 
      return next();
    
  )(req, res, next);
);

module.exports = router;

app/routes/approutes.js

const authMiddleware = require('../middlewares/authMiddleware');

module.exports = function (app) 
  // secure the route by applying authentication middleware
  app.use('/users', authMiddleware);
  .....
  ...
  ..

  // ERROR-HANDLING MIDDLEWARE FOR SENDING ERROR RESPONSES TO MAINTAIN A CONSISTENT FORMAT
  app.use((err, req, res, next) => 
    let responseStatusCode = 500;
    let responseObj = 
      success: false,
      data: [],
      error: err,
      message: 'There was some internal server error',
    ;

    // IF THERE WAS SOME ERROR THROWN BY PREVIOUS REQUEST
    if (!_.isNil(err)) 
      // IF THE ERROR IS REALTED TO JWT AUTHENTICATE, SET STATUS CODE TO 401 AND SET A CUSTOM MESSAGE FOR UNAUTHORIZED
      if (err.name === 'JsonWebTokenError') 
        responseStatusCode = 401;
        responseObj.message = 'You cannot get the details. You are not authorized to access this protected resource';
      
    

    if (!res.headersSent) 
      res.status(responseStatusCode).json(responseObj);
    
  );
;

【讨论】:

以上是关于使用 JWT 进行护照身份验证:如何将护照的默认未经授权响应更改为我的自定义响应?的主要内容,如果未能解决你的问题,请参考以下文章

护照-jwt 总是返回 401 未授权

护照 jwt 验证回调未调用

使用 Passport 进行社交身份验证登录后如何重定向到个人资料页面? (角度,快递,护照,jwt)

如何使用护照身份验证更新包含 jwt 的 cookie

Laravel 通过生成的令牌进行身份验证,无需护照和 jwt

我是不是需要使用快速会话以及护照和 JSON Web 令牌进行身份验证?