npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

hapi-auth-token

v3.0.0

Published

Token authentication for Hapi

Readme

hapi-auth-token

Build Status Coverage Status

This Hapi plugin provides a token based authentication scheme.

The authentication scheme secures endpoints with token authentication, and exposes hooks to validate the received tokens & set custom credentials object onto authenticated Hapi requests (which will be accessible as request.auth.credentials in the route handlers post-authentication). User authentication and token generation should be handled by the application. The scheme will automatically extract auth token from Cookie, Header or Query parameter, making it convenient to use any of those modes for token authentication.

Installation

npm install --save hapi-auth-token

OR

yarn add hapi-auth-token

Example Applications

Usage

Follow these steps to use this plugin in your Hapi application.

  1. Register the plugin
import HapiAuthToken from 'hapi-auth-token';

await server.register(HapiAuthToken)
  1. Configure an auth strategy from the token-auth scheme
const strategyOptions = {
  cookie: {
    name: '__AUTH', // Auth cookie name
    isSecure: false,
  },
  header: false, // Disable extracting token from the "Authorization" header
  query: {
    name: 'authToken', // Name of the query parameter to read the auth token from
  },

  async validateToken(authToken) {
    // Verify whether the token is valid, for example, against a list of existing tokens like below
    return models.UserToken.isValid(authToken);
  },

  async buildAuthCredentials(authToken) {
    // Identify user based on the token information
    // Return a credentials object based on the identified user information
    // The object returned from this method will be accessible as `request.auth.credentials` in authenticated handlers
    const user = await models.User.byAuthToken(authToken);
    return { id: user.id, profile: user.profileId };
  },
};

this._server.auth.strategy('token-auth-strategy', 'token-auth', strategyOptions);

The key parameters in configuration of the strategy are the validateToken and buildAuthCredentials functions.

  • validateToken will be called with the extracted authentication token, and is expected to respond back with a boolean indicating whether the token is valid.
  • buildAuthCredentials will be called if validateToken returns true, and is expected to return a JSON object, which will be set as the auth credentials for the current request. The object returned by this function will be accessible as request.auth.credentials in the authenticated route handlers.

Here's a more elaborate snippet:

import Hapi from 'hapi';
import HapiAuthToken from 'hapi-auth-token';

const server = new Hapi.Server();

async function configureAuth() {
  // Register the HapiAuthToken plugin
  await server.register(HapiAuthToken);

  // Initialize plugin/strategy options
  const strategyOptions = {
    cookie: {
      name: '__AUTH', // Auth cookie name
      isSecure: false,
    },
    header: false, // Disable extracting token from the "Authorization" header
    query: {
      name: 'authToken', // Name of the query parameter to read the auth token from
    },

    async validateToken(authToken) {
      // Verify whether the token is valid, for example, against a list of existing tokens like below
      return models.UserToken.isValid(authToken);
    },

    async buildAuthCredentials(authToken) {
      // Identify user based on the token information
      // Return a credentials object based on the identified user information
      // The object returned from this method will be accessible as `request.auth.credentials` in authenticated handlers
      const user = await models.User.byAuthToken(authToken);
      return { id: user.id, profile: user.profileId };
    },
  };

  // Register an authentication strategy based on the HapiAuthToken scheme
  this._server.auth.strategy('token-auth-strategy', 'token-auth', strategyOptions);
  this._server.auth.default('token-auth-strategy');
}

configureAuth();

API

The plugin can be configured during plugin registration, and/or during auth strategy registration. Options can be passed during plugin registration like this:

await server.register({plugin: HapiAuthToken, options: {<hapi-auth-token-options>}});

Or during strategy registration like this:

server.auth.strategy('<strategy-name>', 'token-auth', {<hapi-auth-token-options>});

Note that the final set of options would be a combination of these two option sets, and the options provided to the strategy will override plugin level options when there's a conflict.

Plugin/Strategy Options

  • cookie
    • false or an object
      • false will disable reading auth tokens from cookies
      • Hapi cookie options object (https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) to configure the auth cookie.
    • name is the name of the auth cookie. Defaults to __TOKEN_AUTH
  • header
    • Boolean indicating whether token authentication via the Authorization header should be enabled
      • If true, the plugin will read auth-token from the Authorization: Token <auth-token> header
      • If false, Authorization headers are ignored by the plugin
      • Defaults to true
  • query
    • false or an object
      • false will disable reading auth tokens from query parameters
      • An options object with the following attributes can be provided to enable reading auth tokens from query parameters
        • name is the name of the query parameter to read the auth token from. Defaults to the token parameter.
    • Defaults to: {name: 'token'}
  • validateToken
    • A function that accepts an auth token (string) and returns a boolean indicating whether the supplied token is valid.
    • This is where you can customize the token validation logic, and this is a required parameter.
  • buildAuthCredentials
    • A function that accepts an auth token (string) and returns a JSON object that would be set as the credentials object on authenticated requests.
    • This will be invoked only if validateToken returns true.
    • The object returned by this function will be accessible as request.auth.credentials in authenticated route handlers.