I've been desperately trying to find a simple method of securing my API but still haven't found one that works. Unlike a lot RESTful APIs my API doesn't need user logins, tokens that expire, or other complex (though very secure) authentication methods, which makes most of the tutorials out there unusable.
The only requirement I have is that a POST request to log a record to my database on one route should be protected while a GET request to access records on that same route should be unprotected. The clients that are logging records are trusted and I would provide their credentials privately.
I've tried using this basic authentication method here:
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
But the POST requests still worked when I used the wrong username and password.
I really don't know what to look for anymore, as I thought basic authentication like that would work.
EDIT: Managed to get this working after changing a couple of things after app.post, which I had overlooked.