Not all parts of your website or REST APIs you do require same level of protection. For example, a GET /api/dimounes
is pretty harmless.
The Express/NodeJS code for such a route may be like follows:
app.get('/api/dimounes/',function(req,res){ var rows = // Get the people from database, file or anywhere res.send(rows); });
Let’s say now you want to add more ‘dimoune’. We create a new route for it but we’ll use HTTP POST verb instead of GET.
app.use(bodyParser.urlencoded({extended: true })); app.use(bodyParser.json()); app.post('/api/dimounes/',function(req,res){ var sql = "INSERT INTO dimounes (name,sex) VALUES ('" + req.body.name + "' , " + req.body.sex + ");"; // run sql or mongo insert res.send("ok"); });
Problem here is everyone can do POST request and spam your database to corrupt it. Let’s protect the POST route so that it requires the user to authenticate.
$ npm install http-auth --save
Let’s define our username and password
var auth = require('http-auth'); var basic = auth.basic({ realm: "Protected Area" }, function (username, password, callback) { // Custom authentication method. callback(username === "nayar" && password === "mydumbpassword"); } );
All we have to do is add auth.connect(basic)
as a middleware in our routes we want to protect
app.post('/api/dimounes/',auth.connect(basic),function(req,res){ var sql = "INSERT INTO dimounes (name,sex) VALUES ('" + req.body.name + "' , " + req.body.sex + ");"; // run sql or mongo insert res.send("ok"); });
And there you go! Let’s try it with AJAX calls with jQuery 😉
$.ajax({ method: "post", url: "/api/dimounes/", data: { name : "Nayar", sex: "male" }, success: function( data ) { console.log(data); }, });
You shall get a popup in your browser asking for your username and password. If you are using curl, just add the credentials using the -u
curl -nayar:mydumbpassword -H "Content-Type:application/json" -X POST --data '{"name":"nayar","sex":"male"}' http://example.com/api/dimounes
NOTE: As we saw in this article (click), Express doesn’t parse HTTP body, we have to add this line at the top for the above command to work in curl.
app.use(bodyParser.json());