Introducing The Sweep: OX’s New Live Security Research Series
Register Now
Breaking: The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Read the Report
Are you exposed? Connect your apps in minutes.
Scan your apps free

hapi-auth-jwt2

Latest version: v11.1.0

Overview

Last scanned
14 Nov 2026
Published
14 Nov 2026
npm package Publisher: nelsonic
793 Stars
124 Forks
1 Versions
312.8K Downloads
JavaScript Repo language

Scan summary

hapi-auth-jwt2 was last scanned on 14 Nov 2026 at version 11.1.0. Risk score 0 of 100. No malicious behavior was detected.

  • Releases: First and only release on 14 Nov 2026.
  • Findings: No rules fired in version 11.1.0.
  • Downloads: 312,761 downloads.

Versions

1 version published
Versions and the rules that fired in each
VersionPublishedStatus
11.1.0 LATEST 14 Nov 2026 No rules fired

No rules fired in 11.1.0

Findings

Findings for v11.1.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.

The score describes 11.1.0; other versions have their own rules, not their own score.

Known vulnerabilities

2 CVEs · last 29 May 2018

1 CRITICAL 1 HIGH 0 MEDIUM 0 LOW

Versions

  • ≥ 5.1.2
  • > 5.1.1, < 5.1.2 1 CRITICAL
  • ≥ 5.1.1, ≤ 5.1.1 1 CRITICAL 1 HIGH
  • < 5.1.1

Vulnerabilities

  • CVE-2016-10525 Critical 29 May 2018 Authentication Bypass in hapi-auth-jwt2 Fixed in 5.1.2
  • NSWG-ECO-81 High No date Authentication Bypass in Try Mode Fixed in 5.1.2

README

The publisher’s own README, as collected from the registry.

Hapi Auth using JSON Web Tokens (JWT)

The authentication scheme/plugin for Hapi.js apps using JSON Web Tokens

GitHub Workflow Status codecov.io HAPI 21.1.0 Node.js Version contributions welcome npm package version

This node.js module (Hapi plugin) lets you use JSON Web Tokens (JWTs) for authentication in your Hapi.js web application.

If you are totally new to JWTs, we wrote an introductory post explaining the concepts & benefits: https://github.com/dwyl/learn-json-web-tokens

If you (or anyone on your team) are unfamiliar with Hapi.js we have a quick guide for that too: https://github.com/dwyl/learn-hapi

Other language documents:

  • 中文文档

Usage

We tried to make this plugin as user (developer) friendly as possible, but if anything is unclear, please submit any questions as issues on GitHub: https://github.com/dwyl/hapi-auth-jwt2/issues

Install from NPM
npm install hapi-auth-jwt2 --save
Example

This basic usage example should help you get started:

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

const people = { // our "users database"
    1: {
      id: 1,
      name: 'Jen Jones'
    }
};

// bring your own validation function
const validate = async function (decoded, request, h) {

    // do your checks to see if the person is valid
    if (!people[decoded.id]) {
      return { isValid: false };
    }
    else {
      return { isValid: true };
    }
};

const init = async () => {
  const server = new Hapi.server({ port: 8000 });
  // include our module here ↓↓, for example, require('hapi-auth-jwt2')
  await server.register(require('../lib/index.cjs'));
  server.auth.strategy('jwt', 'jwt',
  { key: 'NeverShareYourSecret', // Never Share your secret key
    validate  // validate function defined above
  });

  server.auth.default('jwt');

  server.route([
    {
      method: "GET", path: "/", config: { auth: false },
      handler: function(request, h) {
        return {text: 'Token not required'};
      }
    },
    {
      method: 'GET', path: '/restricted', config: { auth: 'jwt' },
      handler: function(request, h) {
        const response = h.response({text: 'You used a Token!'});
        response.header("Authorization", request.headers.authorization);
        return response;
      }
    }
  ]);
  await server.start();
  return server;
}
init().then(server => {
  console.log('Server running at:', server.info.uri);
})
.catch(err => {
  console.log(err);
});

Quick Demo

Open your terminal and clone this repo:

git clone https://github.com/dwyl/hapi-auth-jwt2.git && cd hapi-auth-jwt2

Run the server with:

npm install && node example/server.js

Now (in a different terminal window) use cURL to access the two routes:

No Token Required
curl -v http://localhost:8000/
Token Required

Try to access the /restricted content without supplying a Token (expect to see a 401 error):

curl -v http://localhost:8000/restricted

or visit: http://localhost:8000/restricted in your web browser. (both requests will be blocked and return a 401 Unauthorized error)

Now access the url using the following format: curl -H "Authorization: <TOKEN>" http://localhost:8000/restricted

A here's a valid token you can use (copy-paste this command):

curl -v -H "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6IkFudGhvbnkgVmFsaWQgVXNlciIsImlhdCI6MTQyNTQ3MzUzNX0.KA68l60mjiC8EXaC2odnjFwdIDxE__iDu5RwLdN1F2A" \
http://localhost:8000/restricted

or visit this url in your browser (passing the token in url):

http://localhost:8000/restricted?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6IkFudGhvbnkgVmFsaWQgVXNlciIsImlhdCI6MTQyNTQ3MzUzNX0.KA68l60mjiC8EXaC2odnjFwdIDxE\_\_iDu5RwLdN1F2A&#32;

That's it.

Now write your own validate with what ever checks you want to perform on the decoded token before allowing the visitor to proceed.

Documentation

  • key - (required - unless you have a customVerify function) the secret key (or array of potential keys) used to check the signature of the token or a key lookup function with signature async function(decoded) where:
    • decoded - the decoded but unverified JWT received from client
    • Returns an object { key, extraInfo } where:
      • key - the secret key (or array of keys to try)
      • extraInfo - (optional) any additional information that you would like to use in validate which can be accessed via request.plugins['hapi-auth-jwt2'].extraInfo
    • Throws a Boom error when key lookup fails. Refer to this example implementation and its associated test for a working example.
  • validate - (required) the function which is run once the Token has been decoded with signature async function(decoded, request, h) where:
    • decoded - (required) is the decoded and verified JWT received in the request
    • request - (required) is the original request received from the client
    • h - (required) the response toolkit.
    • Returns an object { isValid, credentials, response } where:
      • isValid - true if the JWT was valid, otherwise false.
      • credentials - (optional) alternative credentials to be set instead of decoded.
      • response - (optional) If provided will be used immediately as a takeover response.
      • errorMessage - (optional defaults to 'Invalid credentials') - the error message raised to Boom if the token is invalid (passed to errorFunc as errorContext.message)
Optional Parameters
  • verifyOptions - (optional defaults to none) settings to define how tokens are verified by the jsonwebtoken library
    • ignoreExpiration - ignore expired tokens
    • audience - do not enforce token audience
    • issuer - do not require the issuer to be valid
    • algorithms - list of allowed algorithms
  • responseFunc - (optional) function called to decorate the response with authentication headers before the response headers or payload is written where:
    • request - the request object.
    • h- the response toolkit.
  • errorFunc - (optional defaults to raising the error requested) function called when an error has been raised. It provides an extension point to allow the host the ability to customise the error messages returned. Passed in object follows the following schema:
    • errorContext - the error object.
      • errorContext.errorType - required the Boom method to call (eg. unauthorized)
      • errorContext.message - required the message passed into the Boom method call
      • errorContext.schema - the schema passed into the Boom method call
      • errorContext.attributes - the attributes passed into the Boom method call
      • errorContext.error - the exception thrown (optional, if available)
      • errorContext.token - the JWT provided, in string form (optional, if available)
      • The function is expected to return the modified errorContext with all above non-optional fields defined.
    • request - the request object.
    • h- the response toolkit.
  • urlKey - (optional defaults to 'token') - if you prefer to pass your token via url, simply add a token url parameter to your request or use a custom parameter by setting urlKey. To disable the url parameter set urlKey to false or ''.
  • cookieKey - (optional defaults to 'token') - if you prefer to set your own cookie key or your project has a cookie called 'token' for another purpose, you can set a custom key for your cookie by setting options.cookieKey='yourkeyhere'. To disable cookies set cookieKey to false or ''.
  • headerKey - (optional defaults to 'authorization') - The lowercase name of an HTTP header to read the token from. To disable reading the token from a header, set this to false or ''.
  • payloadKey - (optional defaults to 'token') - The lowercase name of an HTTP POST body to read the token from. To disable reading the token from a payload, set this to false or ''. Please note, this will not prevent authentication falling through to the payload method unless attemptToExtractTokenInPayload is false
  • tokenType - (optional defaults to none) - allow custom token type, e.g. Authorization: <tokenType> 12345678.
  • complete - (optional defaults to false) - set to true to receive the complete token (decoded.header, decoded.payload and decoded.signature) as decoded argument to key lookup and verify callbacks (not validate)
  • headless - (optional defaults to none) - set to an object containing the header part of the JWT token that should be added to a headless JWT token received. Token's with headers can still be used with this option activated. e.g { alg: 'HS256', typ: 'JWT' }
  • attemptToExtractTokenInPayload - (optional defaults to false) - set to true to let the authenticate method fall through to the payload method for token extraction
  • customExtractionFunc - (optional) function called to perform a custom extraction of the JWT where:
    • request - the request object.
Useful Features
  • The encoded JWT (token) is extracted from the request and made available on the request object as request.auth.token, in case you need it later on in the request lifecycle. This feature was requested by @mcortesi in hapi-auth-jwt2/issues/123
Understanding the Request Flow

At the simplest level this is the request flow through a Hapi App using hapi-auth-jwt2:

verifyOptions let you define how to Verify the Tokens (Optional)

example:

server.auth.strategy('jwt', 'jwt', true,
{ key: 'NeverShareYourSecret', // Never Share your secret key
  validate: validate,      // validate function defined above
  verifyOptions: {
    ignoreExpiration: true,    // do not reject expired tokens
    algorithms: [ 'HS256' ]    // specify your secure algorithm
  }
});

Read more about this at: jsonwebtoken verify options

Specify Signing Algorithm (Optional but highly recommended)

For security reasons it is recommended that you specify the allowed algorithms used when signing the tokens:

server.auth.strategy('jwt', 'jwt', true,
{ key: 'YourSuperLongKeyHere', // Never Share your secret key
  validate: validate,      // validate function defined above
  verifyOptions: { algorithms: [ 'HS256' ] }  // only allow HS256 algorithm
});

If you prefer not to use any of these verifyOptions simply do not set them when registering the plugin with your app; they are all optional.

This feature was requested in: issues/29

Using Base64 encoded secret keys

Some authentication services (like Auth0) provide secret keys encoded in base64, To find out if your authentication service is one of these services, please try and experiment with the base64 encoded secret options on the validator at https://jwt.io

If your key is base64 encoded, then for JWT2 to use it you need to convert it to a Buffer. Following is an example of how to do this.

server.auth.strategy('jwt', 'jwt', true,
{ key: Buffer.from('<Your Base64 encoded secret key>', 'base64'), // Never Share your secret key
  validate: validate,      // validate function defined above
  verifyOptions: { algorithms: [ 'HS256' ] }  // only allow HS256 algorithm
});
Authentication Modes

This plugin supports authentication modes on routes.

  • required - requires JWT to be sent with every request

  • optional - if no JWT is provided, request will pass with request.auth.isAuthenticated set to false and request.auth.credentials set to null

  • try - similar to optional, but invalid JWT will pass with request.auth.isAuthenticated set to false and failed credentials provided in request.auth.credentials

Additional notes on keys and key lookup functions
  • This option to look up a secret key was added to support "multi-tenant" environments. One use case would be companies that white label API services for their customers and cannot use a shared secret key. If the key lookup function needs to use fields from the token header (e.g. x5t header), set option completeToken to true.

  • The reason why you might want to pass back extraInfo in the callback is because you likely need to do a database call to get the key which also probably returns useful user data. This could save you another call in validate.

  • The key or value returned by the key lookup function can also be an array of keys to try. Keys will be tried until one of them successfully verifies the signature. The request will only be unauthorized if ALL of the keys fail to verify. This is useful if you want to support multiple valid keys (like continuing to accept a deprecated key while a client switches to a new key).

server.auth.strategy('jwt', 'jwt', true,
{ key: [ 'PrimareSecretKey', 'DeprecatedKeyStillAcceptableForNow' ],
  validate: validate,
  verifyOptions: { algorithms: [ 'HS256' ] }
});

URL (URI) Token

Several people requested the ability pass in JSNOWebTokens in the requested URL: dwyl/hapi-auth-jwt2/issues/19

Usage

Setup your hapi.js server as described above (no special setup for using JWT tokens in urls)

https://yoursite.co/path?token=your.jsonwebtoken.here

You will need to generate/supply a valid tokens for this to work.

const JWT   = require('jsonwebtoken');
const obj   = { id:123,"name":"Charlie" }; // object/info you want to sign
const token = JWT.sign(obj, secret);
const url   = "/path?token="+token;

What if I want to disable the ability to pass JWTs in via the URL? Set your urlKey to false or ''. (added by @bitcloud: issue #146)

Generating Your Secret Key

@skota asked "How to generate secret key?" in: dwyl/hapi-auth-jwt2/issues/48

There are several options for generating secret keys. The easiest way is to run Node's crypto hash in your terminal:

node -e "console.log(require('crypto').randomBytes(256).toString('base64'));"

and copy the resulting base64 key and use it as your JWT secret.

Want to access the JWT token after validation?

OX Radar and Response Center

Find threats in your stack.

OX Radar can check high-priority threats, like critical package CVEs, against your context.

Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.

Where it’s listed

The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).

  • npm hapi-auth-jwt2

References

The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.

Powered by Read the latest findings

Scan your whole stack

Group 1261154050 1
Group 1261154050
 

From OX Research Newsroom

Cry2Wolf: How to Tell a Real Bug from a Nothingburger
AI & VibeSec

Cry2Wolf: Not Every Branded Bug Deserves a Fire Drill

Vulnerability Insights

OpenSSH Password Authentication Bypass on Alpine Linux (*sshole) – CVE-2026-123158

Copy of Template Design OX Blog (1)
Research

Thousands Of GitHub Accounts Hijacked With wfx-loot CI Secret Stealing Malware Via GitHub Actions & npm

Frame 2085668439 (1)
Group 1261154229