简体   繁体   中英

Express JS Router middlewares

In the code below I want to restrict access to the 'restrictedRoutes' routes without authorization. But in this case 'restrictedRoutes' affects on any routes excluding 'router'.

For example, if I try to access to the '/test', I want to get 404 error, but instead I'm getting JWT-error about invalid token, If that not provided.

How I can create middleware, that will affects only on routes that provided by certain 'Router'?

/*
 * API Routes file
 */
var jwt = require('jsonwebtoken');

var router = require('express').Router();
var restrictedRouter = require('express').Router();

module.exports = function (express, app) {
    //Default routes
    router.get('/login', app.controllers.HomeController.login);

    restrictedRouter.use(function (req, res, next) {
        try {
            var tokenArray = req.headers.authorization.split(' ', 2);
            if (jwt.verify(tokenArray[1], 'shh'))
                next();
        } catch (exception) {
            res.status(401).json({error: exception.message});
        }
    });

    //Restricted routes
    restrictedRouter.get('/', function (req, res) {
        res.send('Success');
    });

    express.use(router);
    express.use(restrictedRouter);
};

Mount the router to some path you want to be restricted.

app.use('/restricted', restrictedRouter);

Also I'd avoid the confusion of passing along express and app like you are doing and instead do it like this:

index.js

var express = require('express');
var app = express();
var routes = require('./routes');

app.use('/restricted', routes.restrictedRouter);
app.use(routes.router);

routes.js

var express = require('express');
exports.router = express.Router();
exports.restrictedRouter = express.Router();

router.get('/login', app.controllers.HomeController.login);

restrictedRouter.use(function (req, res, next) {
    try {
        var tokenArray = req.headers.authorization.split(' ', 2);
        if (jwt.verify(tokenArray[1], 'shh'))
            next();
    } catch (exception) {
        res.status(401).json({error: exception.message});
    }
});

//Restricted routes
restrictedRouter.get('/', function (req, res) {
    res.send('Success');
});

Your other option is to use the middleware per route:

var authMiddleware = function (req, res, next) {
  try {
    var tokenArray = req.headers.authorization.split(' ', 2);
    if (jwt.verify(tokenArray[1], 'shh'))
        next();
  } catch (exception) {
    res.status(401).json({error: exception.message});
  }
});

router.get('/', authMiddleware, function(req, res) {
   res.send('Success');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM