MonkeyBonkey
MonkeyBonkey

Reputation: 47871

chaining request filters through plugins in hapi.js

I need to validate a client-key as well as a jsonwebtoken header in all my requests to a hapi.js rest api.

I am currently using the hapi-auth-jwt plugin to handle the json web tokens - and now I'd also like to put in a handler that checks for a valid client key in the api header upstream - before it does any of the web token checks and everything else - so that it can quickly return a 401 if a valid client-api-key is not included.

Should I do this as a plugin in hapi? If so how do I set order of the plugins that run - is it simply the order that I register the plugins?

How do I set the plugin to intercept all http requests - should I make it an auth scheme?

exports.register = function (server, options, next) { 
// do I somehow set a default request handler here somehow?
}

Upvotes: 2

Views: 1313

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

You can register an extension function for the available extension points in the Hapi Request lifecycle.

In your case, since you want the request to be validated for a valid client-api-key before being authenticated, the extension function can be registered for onRequest or onPreAuth events.

exports.register = function (server, options, next) { 

    server.ext('onRequest', function (request, reply){

        //Validate the request object here.

        if (valid) reply.continue();
        else reply(Boom.unauthorized('Invalid API Key'));
    });

    next();
}

Upvotes: 2

Related Questions