Express + JWT 排除某些路由

Express + JWT exclude certain routes

我有一个 Node 应用程序 运行 expressjsonwebtoken。在 api 的每个请求调用之前,我都进行了检查以检查 jsonwebtoken。我已经手动排除了如下所示的路线。有没有更好的方法可以从中排除某些路线?我该怎么做?

import * as express from 'express';
import * as jwt from 'jsonwebtoken';

import UserCtrl from './controllers/user';

export default function setRoutes(app) {

  const router = express.Router();

  // route middleware to verify a token
  router.use(function (req, res, next) {
    if ((req.method == 'POST' || req.method == 'OPTIONS') && (req.url == '/user' || req.url == '/login' || req.url == '/user/activate')) {
      next();
    } else {
      // check header or url parameters or post parameters for token
      var token = req.headers.authorization;
      // decode token
      if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function (err, decoded) {
          if (err) {
            return res.status(401).send({
              success: false,
              message: 'Sign in to continue.'
            });
          } else {
            // if everything is good, save to request for use in other routes
            next();
          }
        });
      } else {
        // if there is no token
        // return an error
        return res.status(401).send({
          success: false,
          message: 'Sign in to continue.'
        });
      }
    }
  });

  const userCtrl = new UserCtrl();

  router.route('/login').post(userCtrl.login);
  router.route('/user/activate').post(userCtrl.activate);
  router.route('/users').get(userCtrl.getAll);
  router.route('/users/count').get(userCtrl.count);
  router.route('/user').post(userCtrl.signup);
  router.route('/user/:id').get(userCtrl.get);
  router.route('/user/:id').put(userCtrl.update);
  router.route('/user/:id').delete(userCtrl.delete);

  app.use('/api/v1', router);
}

您可以提取函数(验证令牌的函数)并将其用作路由器中特定路由的中间件。这样你就不必在函数内指定哪些路由需要登录。

像这样:

function isLoggedIn(req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.headers.authorization;
    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function(err, decoded) {
            if (err) {
                return res.status(401).send({
                    success: false,
                    message: 'Sign in to continue.'
                });
            } else {
                // if everything is good, save to request for use in other routes
                next();
            }
        });
    } else {
        // if there is no token
        // return an error
        return res.status(401).send({
            success: false,
            message: 'Sign in to continue.'
        });
    }
}

const userCtrl = new UserCtrl();

// Routes that require no login
router.post('/login', userCtrl.login);
router.get('/users', userCtrl.getAll);
router.post('/user/activate', userCtrl.activate);

// Routes that require login
router.get('/users/count', isLoggedIn, userCtrl.count);
router.post('/user', isLoggedIn, userCtrl.signup);
router.get('/user/:id', isLoggedIn, userCtrl.get);
router.put('/user/:id', isLoggedIn, userCtrl.update);
router.delete('/user/:id', isLoggedIn, userCtrl.delete);

app.use('/api/v1', router);

您可以阅读有关 Express Middlewares here 的更多信息。

你可以做到

app.use(
  jwt({ secret, algorithms: ['HS256'] }).unless({ path: ['/foo/bar'] }),
);