Hapi API

Community maintained

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

This tutorial shows you how to use the authorization features in the OAuth 2.0 framework to limit access to your or third-party applications. For more information, read the API authorization documentation.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your 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

Add API Authorization

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is stored in the access token created for the user and needs to be sent in the Authorization header. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating access tokens, read the Verify Access Tokens tutorial.

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 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. You can access this public key 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.

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

  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 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.

Make a Call to Your API

To make calls to your API, you need an access token. You can get an access token for testing purposes from the test lab in your API settings.

Obtain a JWT

Provide the access token as an Authorization header in your requests.


curl --request GET \
  --url http://your-domain.com/api_path \
  --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("http://your-domain.com/api_path");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
IRestResponse response = client.Execute(request);
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "http://your-domain.com/api_path"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.get("http://your-domain.com/api_path")
  .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://your-domain.com/api_path",
  "method": "GET",
  "headers": {
    "authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require("request");

var options = { method: 'GET',
  url: 'http://your-domain.com/api_path',
  headers: { authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://your-domain.com/api_path"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://your-domain.com/api_path",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
import http.client

conn = http.client.HTTPConnection("your-domain.com")

headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }

conn.request("GET", "/api_path", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("http://your-domain.com/api_path")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE'

response = http.request(request)
puts response.read_body
import Foundation

let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]

var request = NSMutableURLRequest(URL: NSURL(string: "http://your-domain.com/api_path")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

Use Auth0 for FREECreate free Account