简体   繁体   中英

middleware that run before any routes

I'm trying to do a token based auth. I'm stuck at running auth before any request happens. For example below code is to get the users, but one middleware should check whether the request has valid token or not.

app.js

var user = require('./controllers/user');
app.use('/api', user);

user.js

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

router.get('/user', function(req, res) {
  User.find({}, function(err, users) {
    res.json(users);
  });
});

module.exports = router;

I have that logic which is here , but I don't know where to place it.

Put your middleware before everything :)

 var app = express(); function myCustomMiddleware(req, res, next) { if(/**something we need **/) { req.haveWhatWeNeed = true; } return next(); } app .use(myCustomMiddleware) .get(/*** everything you want***/) ; 

您可以在定义任何路由之前定义中间件,以确保在被路由处理之前执行它们。

In your app.js register the token authentication middleware with express' app.use() before any routes.

This way the token authentication will be executed everytime a route defined after is called. Basically app.use(authentication) is the same as app.use('*', authentication), which means that the middleware is executed for all the domains, not just for '/api'.

auth.js

module.exports = function(req, res, next) {

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.param('token') || req.headers['x-access-token'];

    // decode token
    if (token) {

        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {          
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });      
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;  
                next();
            }
        });

    } else {

        // if there is no token
        // return an error
        return res.status(403).send({ 
            success: false, 
            message: 'No token provided.'
        });

    }

};

app.js

var express = require("express");
var app = module.exports = express();

// put the middleware before any routes in app.use()
var authentication = require("./middleware/auth");
app.use(authentication);

var user = require('./controllers/user');
app.use('/api', user);

If you want to have the token check only for the '/api' routes, then define the authentication just for that with

app.use('/api', authentication, user);

app.use() runs the functions given as parameters in given order.

What I understand from your question is that before executing the code for route you need a middleware check.

    var middlewareFunction = function(req, res, next) {

        // check header or url parameters or post parameters for token
        var token = req.body.token || req.param('token') || req.headers['x-access-token'];

        // decode token
        if (token) {

            // verifies secret and checks exp
            jwt.verify(token, app.get('superSecret'), function(err, decoded) {          
                if (err) {
                    return res.json({ success: false, message: 'Failed to authenticate token.' });      
                } else {
                    // if everything is good, save to request for use in other routes
                    req.decoded = decoded;  
                    next();
                }
            });

        } else {

            // if there is no token
            // return an error
            return res.status(403).send({ 
                success: false, 
                message: 'No token provided.'
            });

        }
}

Make a middleware function as such and in your route add this function..

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

router.get('/user', middlewareFunction, function(req, res, next) {
  User.find({}, function(err, users) {
    res.json(users);
  });
});

module.exports = router;

I hope this solves your issue.

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