jwt

JWT (JSON Web Token) Authentication.

Latest Version: 3.2.0
hapi-family
Installation:

npm: npm install @hapi/jwt

yarn: yarn add @hapi/jwt

Module Status:
Version License Node Dependencies CI
3.2.0
hapi helmet github logo
BSD 16, 18, 20 Dependency Status Build Status
2.1.1
hapi helmet github logo
BSD 16, 18, 20 Dependency Status Build Status

Introduction

jwt is part of the hapi ecosystem and was designed to work seamlessly with the hapi web framework and its other components (but works great on its own or with other frameworks). If you are using a different web framework and find this module useful, check out hapi – they work even better together.

Usage

// Load modules

const Jwt = require('@hapi/jwt');
const Hapi = require('@hapi/hapi');

// Declare internals

const internals = {};

internals.start = async function () {

    const server = Hapi.server({ port: 8000 });

    // Register jwt with the server

    await server.register(Jwt);

    // Declare an authentication strategy using the jwt scheme.
    // Use keys: with a shared secret key OR json web key set uri.
    // Use verify: To determine how key contents are verified beyond signature.
    // If verify is set to false, the keys option is not required and ignored.
    // The verify: { aud, iss, sub } options are required if verify is not set to false.
    // The verify: { exp, nbf, timeSkewSec, maxAgeSec } parameters have defaults.
    // Use validate: To create a function called after token validation.

    server.auth.strategy('my_jwt_strategy', 'jwt', {
        keys: 'some_shared_secret',
        verify: {
            aud: 'urn:audience:test',
            iss: 'urn:issuer:test',
            sub: false,
            nbf: true,
            exp: true,
            maxAgeSec: 14400, // 4 hours
            timeSkewSec: 15
        },
        validate: (artifacts, request, h) => {

            return {
                isValid: true,
                credentials: { user: artifacts.decoded.payload.user }
            };
        }
    });

    // Set the strategy

    server.auth.default('my_jwt_strategy');
};

internals.start();