Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding middleware to check API key & pass

I am just starting out learning node.js after deciding to write my next API using node and restify. There will only be a couple of users accessing the API and it will be a strictly private one - no one else should be able to access it.

Basically, I need away to check that "key" and "pass" params are supplied (and valid) for every request. So, I thought I could add some middleware that is executed before everything else to do the checking.. e.g.:

var restify = require('restify');

var server = restify.createServer({
    name: 'test'
});

server.use(function(req, res, next) {
    if (req.params.key == null) {
        console.log("No API key supplied");
        return next(new restify.NotAuthorizedError("No API key supplied"));
    }
});
server.use(restify.bodyParser());


server.listen(8888, function() {
    console.log('%s listening at %s', server.name, server.url);
});

server.get('/test', function(req, res, next) {
    res.send('Hello World');
    return next();
});

Browsing to localhost:8888/test gives {"code":"NotAuthorized","message":"No API key supplied"} which is what I want.

However, browsing to http://localhost:8888/test?key=a still gives the same message..

Clearly, I'm not going about this the right way. Can someone point me in the right direction?

Thanks in advance.

like image 703
cud_programmer Avatar asked Jun 06 '26 17:06

cud_programmer


1 Answers

I needed to add restify.queryParser() to parse the GET params. Now, this works:

var restify = require('restify');

var server = restify.createServer({
    name: 'test'
});

server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(function(req, res, next) {
    if (req.query.key == null) {
        console.log("No API key supplied");
        return next(new restify.NotAuthorizedError("No API key supplied"));
    } else return next();
});

server.listen(8888, function() {
    console.log('%s listening at %s', server.name, server.url);
});

server.get('/test', function(req, res, next) {
    res.send('Hello World');
    return next();
});
like image 180
cud_programmer Avatar answered Jun 08 '26 09:06

cud_programmer