Scan your whole stack
From OX Research Newsroom
Are you using hapi-auth-jwt2?
Find out what’s in your code.
Scan your apps free in minutes (opens in a new tab)Latest version: v11.1.0
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.
| Version | Published | Status |
|---|---|---|
| 11.1.0 LATEST | 14 Nov 2026 | No rules fired |
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.
1 CRITICAL 1 HIGH 0 MEDIUM 0 LOW
The publisher’s own README, as collected from the registry.
The authentication scheme/plugin for Hapi.js apps using JSON Web Tokens
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:
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
npm install hapi-auth-jwt2 --save
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);
});
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:
curl -v http://localhost:8000/
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):
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.
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{ 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'].extraInfovalidate - (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 requestrequest - (required) is the original request received from the clienth - (required) the response toolkit.{ 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)verifyOptions - (optional defaults to none) settings to define how tokens are verified by the
jsonwebtoken libraryignoreExpiration - ignore expired tokensaudience - do not enforce token audienceissuer - do not require the issuer to be validalgorithms - list of allowed algorithmsresponseFunc - (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 callerrorContext.schema - the schema passed into the Boom method callerrorContext.attributes - the attributes passed into the Boom method callerrorContext.error - the exception thrown (optional, if available)errorContext.token - the JWT provided, in string form (optional, if available)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 falsetokenType - (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 extractioncustomExtractionFunc - (optional) function called to perform a custom extraction of the JWT where:request - the request object.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/123At the simplest level this is the request flow through a Hapi App
using hapi-auth-jwt2:
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
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
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
});
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
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' ] }
});
Several people requested the ability pass in JSNOWebTokens in the requested URL: dwyl/hapi-auth-jwt2/issues/19
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
urlKeytofalseor ''. (added by @bitcloud: issue #146)
@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.
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.
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).
The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.