简体   繁体   中英

NodeJS, Express, Mongoose RESTFul Api access only by the server itself

I've built a simple RESTful API using NodeJS, Mongoose, and Express. I am using the database to store simple string quotes and am not planning to allow access to any other users to the database nor to the api.

I've read up on securing my RESTful API but it seems as if most methods focus on using a username and password to limit access. However, that seems like an overkill for such a simple API especially since i do not consider on allowing anyone else access except for requests that come from the server itself.

So I want to make it so that if anyone else tries to access the API he would be denied access. The only way the API should be accessible is from requests from the server itself ie from the JavaScript files on the server.

I am currently learning all those things so sorry if i am not using the proper technical terminology :)

I am considering doing something like checking the IP of the person/thing trying to access the API and if that is not the ip of the server then deny access. Would something like this work and how would I got about implementing it.

EDIT: I am looking for something simple since I dont think that most people will take the time to 'hack' the API just so they can access a database of quotes.

Here is my server.js

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var mongoose   = require('mongoose');
var Quote     = require('./mongodb/models/mainModel.js');
mongoose.connect('mongodb://localhost:27017/myappdb');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

var router = express.Router();

function grantAccess(req) {
  if(req.ip === '::1'  ||
     req.ip === '127.0.0.1' ||
     req.ip === '::ffff:127.0.0.1') {
    return true;
  }
  return ["IP Address Unknown " + req.ip]
}

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.route('/maindb')

    .post(function(req, res) {

        var quote = new Quote();    
        quote.name = req.body.name; 
        quote.severity = req.body.severity;
        quote.createdAt = new Date();
        quote.updatedAt = new Date();

        quote.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Quote created!' });
        });

    })

    .get(function(req, res) {
        if(grantAccess(req) !== 'boolean')
        Quote.find(function(err, quotes) {
            if (err)
                res.send(err);

            res.json(quotes);
        });
    });

    router.route('/maindb/:quote_id')
        .get(function(req, res) {
            Quote.findById(req.params.quote_id, function(err, quote) {
                if (err)
                    res.send(err);
                res.json(quote);
            });

        })
        .put(function(req, res) {


            Quote.findById(req.params.quote_id, function(err, quote) {

                if (err)
                    res.send(err);

                quote.name = req.body.name;
                quote.severity = req.body.severity;
                quote.updatedAt = new Date();
                // save the bear
                quote.save(function(err) {
                    if (err)
                        res.send(err);

                    res.json({ message: 'Quote updated!' });
                });

            });
        })
        .delete(function(req, res) {
            Quote.remove({
                _id: req.params.quote_id
            }, function(err, quote) {
                if (err)
                    res.send(err);

                res.json({ message: 'Successfully deleted' });
            });
        });


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

app.listen(port);
console.log('Magic happens on port ' + port);

you can add apiKey in your project. It will be required if anyone hits any of your api.

exmaple:

"apiKeys": {
        "web":     "7fe642cabe6855cd4175937fa8fadd876c1af6b499ab941db6a8a362c0f30f97"
    }

similarly you can set apikey for mobile user or accordance to requirment of project.

Link to genrate RandomKey

By this you will allow only those users who have your api key.As api key is shared by you so you will provide it to only appropriate user.

Api key checking:

You can check api key as first middleware before any request to server

example:

router.use(function(req,res,next){
var apiKey = req.get('api_key'); // assuming user will send api key in headers
// code to check api key basic comparison
})

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