Hapi API: Authorization

View on Github

Hapi API: Authorization

Community maintained

This tutorial demonstrates how to add authorization to a Hapi.js API. We recommend you to Log in to follow this quickstart with examples configured for your account.

Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Hapi.js 16.0.0 | hapi-auth-jwt2 7.2.4

New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.

Configure Auth0 APIs

Create an API

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API, for example https://quickstarts/api. You will use the identifier as an audience later, when you are configuring the Access Token verification. For Signing Algorithm, select RS256.

Create API

By default, your API uses RS256 as the algorithm for signing tokens. Since RS256 uses a private/public keypair, it verifies the tokens against the public key for your Auth0 account. The public key is in the JSON Web Key Set (JWKS) format, and can be accessed here.

We recommend using the default RS256 signing algorithm for your API. If you need to use the HS256 algorithm, see the HS256 integration sample.

Define scopes

Scopes let you define which resources can be accessed by the user with a given Access Token. For example, you might choose to grant read access to the messages resource if users have the manager access level, and a write access to that resource if they have the administrator access level.

You can add the required scopes in the Scopes tab of the Auth0 Dashboard's APIs section.

Configure Scopes

This example uses the read:messages scope.

This example demonstrates:

  • How to check for a JSON Web Token (JWT) in the Authorization header of an incoming HTTP request.

  • How to check if the token is valid, using the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating Access Tokens, read the Verify Access Tokens tutorial.

Validate Access Tokens

Install dependencies

This guide shows you how to validate the Access Token using the hapi-auth-jwt2 plugin. 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

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 a function which is the final stop for accepting or rejecting authorization for a given request. This function must return a callback with either true or false to indicate the request can proceed. The function can also operate on the decoded payload of the JWT and supply a modified req.auth.credentials object based on custom logic.

When you request multiple scopes in an Auth0 authentication transaction, they come back as a space-delimited string in the Access Token payload. However, the hapi-auth-jwt2 plugin expects an array when multiple scopes are used. This conversion can be handled in the validateFunc function.

Add a function called validateUser and modify the req.auth.credentials object such that the scope key is parsed into an array instead of a space-delimited string.

// 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) {
    if (decoded.scope)
      return callback(null, true, {
        scope: decoded.scope.split(' ')
      });

    return callback(null, true);
  }

  return callback(null, false);
};

When a valid JWT Access Token is received at an endpoint, the scopes from the payload will be available as an array on req.auth.credentials.

Protect API Endpoints

The routes shown below are available for the following requests:

  • GET /api/public: available for non-authenticated requests
  • GET /api/private: available for authenticated requests containing an Access Token with no additional scopes
  • GET /api/private-scoped: available for authenticated requests containing an Access Token with the read:messages scope granted

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. To protect a route requiring a valid JWT you can pass auth: 'jwt'.

The routes shown below are available for the following requests:

  • GET /api/public: available for non-authenticated requests
  • GET /api/private: available for authenticated requests containing an Access Token with no additional scopes
  • GET /api/private-scoped: available for authenticated requests containing an Access Token with the read:messages scope granted
// server.js

// This route doesn't need authentication
server.route({
  method: 'GET',
  path: '/api/public',
  config: {
    auth: false,
    handler: (req, res) => {
      res({
        message: "Hello from a public endpoint! You don't need to be authenticated to see this."
      });
    }
  }
});

// This route need authentication
server.route({
  method: 'GET',
  path: '/api/private',
  config: {
    auth: 'jwt',
    handler: (req, res) => {
      res({
        message: 'Hello from a private endpoint! You need to be authenticated to see this.'
      });
    }
  }
});

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 authentication 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-scoped',
  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.

Use Auth0 for FREE