Should I create a hapijs plugin or use server.ext to display the api key in the header

So I would like to check all http routes to my hapi rest api for a valid api key. I don't want to use the auth plugin as I will also have basic auth on some routes in addition to validating the api token. I'm used to doing this as middleware in express, but what's the right way to go in hapi?

Should I create my own plugin or use server.ext instead to accomplish this .. or should I do it another way?

So far this has been the way I did it

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

    //make sure its https
    if(request.headers['x-forwarded-proto'] && request.headers['x-forwarded-proto'] === "http") {
        return next(Boom.badRequest('ssl is required'));
    }
    else
    {
        if (request.headers['x-api-key'] != apiToken) {
            return next(Boom.unauthorized('api key is incorrect'));
        }
        else
        {
            next();
        }
    }
});

      

+3


source to share


2 answers


I would use an authentication plugin. You can use several authentication strategies at the same time, but not limited to them. Here's an example of how to do it:

var Hapi = require('hapi');
var server = new Hapi.Server(3000);

server.pack.register([require('hapi-auth-basic'), require('hapi-auth-cookie')], function(err) {

  server.auth.strategy('simple', 'basic', { ... });
  server.auth.strategy('session', 'cookie', { ... });

  server.route({
    method: 'GET',
    path: '/',
    auth: {
      strategies: ['simple', 'session']
    },
    handler: function(request, reply) {
      reply('success');
    }
  });

  server.start(function() {
    console.log('Server running at:', server.info.uri);
  });

});

      



For details see Authentication :

When specifying one strategy, you can set the property strategy

to a string with the name of the strategy. When specifying more than one strategy, the parameter name must be strategies

and must be an array of strings, each of which names the strategy to try. Strategies then try to do this until you succeed, or they all fail.

+1


source


While Gergo's answer is good, I have a similar use case where I also need strategies to behave in such a way that:

A (Succeed) --> B (Succeed) --> Handler

A (Fail) --> reply(4xx) || A(succeed) --> B (fail) --> reply(4xx)

      



I processed it this way

server.ext('onPostAuth', function(request, reply) {
  request.server.auth.test('A', request, function(err) {
    return err ? reply(err) : reply.continue();
  });
});

server.ext('onPostAuth', function(request, reply) {
  request.server.auth.test('B', request, function(err) {
    return err ? reply(err) : reply.continue();
  });
});

      

0


source







All Articles