Express ip filter for specific routes?

前端 未结 3 823
难免孤独
难免孤独 2021-02-09 20:44

Is it possible to apply different ip filters to different routes?

For example, I want only people from 123.123.123.123 can access my server\'s /test route,

相关标签:
3条回答
  • 2021-02-09 21:04

    Yeah, it's possible. You could do something like:

    app.get('/test', function(req, res){
        var trustedIps = ['123.123.123.123'];
        var requestIP = req.connection.remoteAddress;
        if(trustedIps.indexOf(requestIP) >= 0) {
            // do stuff
        } else {
            // handle unallowed ip
        }
    })
    

    You may need to make sure that requestIP is correctly formatted though.

    0 讨论(0)
  • 2021-02-09 21:26

    Warning: package express-ipfilter is now deprecated.

    You can chain middlewares (and ipFilter is a middleware). There are 2 ways to do this:

    var express = require('express'),
        ipfilter = require('express-ipfilter').IpFilter;
    
    var ips = ['::ffff:127.0.0.1'];
    var testers = ['1.2.3.4'];
    var app = express();
    
    app.get('/test', ipfilter(testers, {mode: 'allow'}), function(req, res) {
        res.send('test');
    });
    
    
    // the ipfilter only applies to the routes below  
    app.get('/', ipfilter(ips, {mode: 'allow'}), function(req, res) {
        res.send('Hello World');
    });
    
    app.listen(3000);
    

    Or qualify the use of the middleware:

    var express = require('express'),
        ipfilter = require('express-ipfilter').IpFilter;
    
    var ips = ['::ffff:127.0.0.1'];
    var testers = ['1.2.3.4'];
    var app = express();
    
    app.use('/test', ipfilter(testers, {})); // the ipfilter only applies to the routes below    
    
    app.get('/test', function(req, res) {
        res.send('test');
    });
    
    app.use('/', ipfilter(ips, {})); // the ipfilter only applies to the routes below
    
    app.get('/', function(req, res) {
        res.send('Hello World');
    });
    
    app.listen(3000);
    
    0 讨论(0)
  • 2021-02-09 21:26

    In your main file where u defined app,

    app.use('/test',require('./whereever-my-route-is-located-where /test routes '));
    app.use('/',require('./wherever-my-this-routes-are-located'))
    

    in your route file .

    var express = require('express'),
        router = express.Router();
    //Ip verification for all requests : for whereever-my-route-is-located-where /test routes 
    router.use(function(req, res, next) {
        //verify Ip Logic
    });
    //this will be called for every route u define in that file, if it fails.
    
    0 讨论(0)
提交回复
热议问题