Hapi API Authorization

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Hapi.js 16.0.0
  • hapi-auth-jwt2 7.2.4
Show requirements

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. There are various methods for including authorization information in a request, but for integration with Auth0, your API needs to check for a valid JSON Web Token (JWT). When users log into your application, they will receive an id_token and an access_token which are both JWTs. The specific JWT that needs to be sent to your API is the access_token.

This sample demonstrates how to check for a JWT in the Authorization header of an incoming HTTP request and verify that it is valid. The validity check is done using the hapi-auth-jwt2 plugin and can be applied to any endpoints you wish to protect. If the token is valid, the resources which are served by the endpoint can be released, otherwise a 401 Authorization error will be returned.

Install the Dependencies

The hapi-auth-jwt2 plugin can be used to verify incoming JWTs. The jwks-rsa library can be used alongside it to fetch your Auth0 public key and complete the verification process. Install these libraries with npm.

npm install --save hapi-auth-jwt2 jwks-rsa

Configure hapi-auth-jwt2

By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json.

It is highly recommended that you use the default signing algorithm of RS256 for your API. If you do require HS256 as the algorithm, see the HS256 integration sample.

Set up the hapi-auth-jwt2 plugin to fetch this public key through the jwks-rsa library.

// server.js

const Hapi = require('hapi');
const jwt = require('hapi-auth-jwt2');
const jwksRsa = require('jwks-rsa');

const server = new Hapi.Server();

// ...

server.register(jwt, err => {
  if (err) throw err;
  server.auth.strategy('jwt', 'jwt', 'required', {
    complete: true,
    // verify the access token against the
    // remote Auth0 JWKS 
    key: jwksRsa.hapiJwt2Key({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
    }),
    verifyOptions: {
      audience: '{YOUR_API_IDENTIFIER}',
      issuer: `https://YOUR_AUTH0_DOMAIN/`,
      algorithms: ['RS256']
    },
    validateFunc: validateUser
  });
  registerRoutes();
});

The hapi-auth-jwt2 plugin does the work of actually verifying that the JWT is valid. However, the validateFunc key requires some function that can do further checking. This might simply be a check to ensure the JWT has a sub claim, but your needs may vary in your own application.

// server.js

const validateUser = (decoded, request, callback) => {
  // This is a simple check that the `sub` claim
  // exists in the access token. Modify it to suit
  // the needs of your application
  if (decoded && decoded.sub) {
    return callback(null, true);
  }

  return callback(null, false);
}

Protect Individual Endpoints

The configuration that is set up above for the hapi-auth-jwt2 plugin specifies required as the third argument to the strategy. This means that all routes will require authentication by default. If you'd like to make a route public, you can simply pass auth: false to the route's config.

So far, the API is only checking for whether the incoming request has valid authentication information. This solves the case of restricting endpoints such that only authenticated users can access them; however, it doesn't currently provide any way to check for authorization.

Authorization can be added to your authenitcation flow by use of a scope claim in the access_token which provides some indication of what that token allows access to. For more information on how to add scopes to an access_token, see the Scopes documentation.

Individual routes can be configured to look for a particular scope in the access_token using auth.scope.

// server.js

// ...

server.route({
  method: 'GET',
  path: '/api/private',
  config: {
    auth: {
      scope: 'read:messages'
    },
    handler: (req, res) => {
      res({ message: "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this." });
    }
  }
});

With this configuration in place, only valid access_tokens which have a scope of read:messages will be allowed to access this endpoint.

Previous Tutorial
1. Getting Started
Use Auth0 for FREECreate free Account