简体   繁体   English

仅服务器本身可以访问NodeJS,Express,Mongoose RESTFul Api

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

I've built a simple RESTful API using NodeJS, Mongoose, and Express. 我使用NodeJS,Mongoose和Express构建了一个简单的RESTful API。 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. 我正在使用数据库存储简单的字符串引号,并且不打算允许任何其他用户访问数据库或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. 我已经阅读过有关保护RESTful API的信息,但似乎大多数方法都集中在使用用户名和密码来限制访问。 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. 但是,对于这样一个简单的API来说,这似乎是一个矫kill过正,尤其是因为我不考虑允许除服务器本身发出的请求之外的任何其他人进行访问。

So I want to make it so that if anyone else tries to access the API he would be denied access. 因此,我想这样做,以便如果其他人尝试访问该API,则将拒绝该访问。 The only way the API should be accessible is from requests from the server itself ie from the JavaScript files on the server. 应该可以访问API的唯一方法是来自服务器本身的请求,即来自服务器上的JavaScript文件。

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. 我正在考虑做一些事情,例如检查试图访问API的人的IP,如果不是服务器的IP,则拒绝访问。 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. 编辑:我正在寻找简单的东西,因为我认为大多数人不会花时间来“破解” API,以便他们可以访问报价数据库。

Here is my server.js 这是我的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. 您可以在项目中添加apiKey。 It will be required if anyone hits any of your api. 如果有人点击您的任何api,则将需要该文件。

exmaple: 例如:

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

similarly you can set apikey for mobile user or accordance to requirment of project. 同样,您可以为移动用户或根据项目要求设置apikey。

Link to genrate RandomKey 链接以生成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密钥的用户。由于api密钥由您共享,因此您只能将其提供给适当的用户。

Api key checking: api密钥检查:

You can check api key as first middleware before any request to server 您可以在对服务器的任何请求之前将api密钥检查为第一个中间件

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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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