hapi — Define Multiple Authentication Strategies for a Route

The last tutorials within this hapi series walked you through the details of basic authentication with hapi and how to remember users leveraging cookies and also how to explicitly set a default authentication strategy.

Within this guide, you’ll learn how to allow multiple authentication strategies for individual routes.

Before diving into the details, have a look at the series outline and find posts that match your interests and needs.

hapi Series Overview

Preparation

Actually, we guess you’ve already created your hapi based project. Nonetheless, to get everyone on the same page let’s shortly recap what this guide is about.

First, create your hapi server instance, define the connection settings and afterwards register your desired plugins. Up to this point, you should be familiar with the code snippet below. If you don’t feel comfortable, just wind back and read the tutorial on how to extend your hapi server using plugins.

const Hapi = require('hapi')

// create new server instance
const server = new Hapi.Server()

async function liftOff() {  
  server.register([
    {
      plugin: require('hapi-auth-basic')
    },
    {
      plugin: require('hapi-auth-cookie')
    }
  ])

  // TODO: add authentication strategies
  // TODO: define default auth strategy
  // TODO: add routes

  try {
    await server.start()
    console.log('info', 'Server running at: ' + server.info.uri)
  } catch (err) {
    console.error(err)
    process.exit(1)
  }
}

liftOff()  

The snippet above outlines the fundamental steps to create your hapi server and register two plugins that can be used to prepare authentication within your app.

Register Authentication Strategies

You’re not right at the point of defining multiple authentication strategies for a route, because the server setup isn’t complete to actually use the registered auth plugins. You need to create authentication strategies based on the newly available authentication schemes. You can find more information about the individual authentication types within the detailed tutorials on basic authentication with hapi and session based authentication using cookies in hapi.

// register your auth strategies

server.auth.strategy('simple', 'basic', { validateFunc: basicValidationFn })  
server.auth.strategy('session', 'cookie', { password: '…' })  

Once you have more than a single authentication strategies available, you need to define a default one. Last week’s guide walks you through two different types on how to set a default authentication strategy. For now, you can go ahead and set a default strategy using the following line of code:

// default auth strategy avoids server crash for routes without auth config
server.auth.default('simple')  

Basically, you only need to define a default authentication strategy if you’ve created multiple authentication strategies and also have routes available that don’t specify an auth configuration. In those cases, hapi will throw an error to indicate this issue right at server start. Even though that’s annoying, there’s no rude surprise during runtime.

Configure Multiple Strategies for a Route

Finally, you’re at the point of defining multiple authentication strategies for your routes. You’re using the same auth config object as you would do within your previous authentication setup. The thing that changed is the field you’re going to set, namely strategies with an array of authentication strategy names.

server.route({  
  method: 'GET',
  path: '/profile',
  config: {
    auth: {
      strategies: ['simple',  'session']
    },
    handler: (request, h) => {
      return h.view('profile')
    }
  }
})

Within the preparation part of this tutorial, you’ve created two authentication strategies: simple and session. Within the route configuration above, you’re allowing both strategies to access the /profile path.

That’s the trick to allow multiple authentication strategies for your routes!

When to Use Multiple Authentication Strategies for a Route?

Actually, there are various use cases and scenarios to apply more than just a single strategy. For example, we at Future Studio use multiple auth strategies for the endpoint to create short-links from tutorial urls. Precisely, anyone within the team can create a short-link from an access restricted web view and also via an API call (using Postman or any other client) that requires authentication via a JWT token.

Outlook

Allowing multiple authentication strategies is beneficial in various scenarios. This guide shows you the details that are required to define multiple, different authentication strategies for your routes.

We appreciate feedback and love to help you if there’s a question in your mind. Let us know in the comments or on twitter @futurestud_io.

Make it rock & enjoy coding!


Additional Resource

Explore the Library

Find interesting tutorials and solutions for your problems.