hapi auth bearer token
Release Notes for Version 6.0.x which only supports hapi v17 and above.
Note: For hapi versions below v17, you must use versions v5.x.x of this module.
Lead Maintainer: John Brett
Bearer authentication requires validating a token passed in by bearer authorization header or query parameter.
This module creates a 'bearer-access-token'
scheme takes the following options:
validate
- (required) a token validation function with the signature [async] function(request, token, h)
where:
request
- is the hapi request object of the request which is being authenticated.token
- the auth token received from the client.h
- the response toolkit.- Returns an object
{ isValid, credentials, artifacts }
where:
isValid
- true
if token is valid, otherwise false
.credentials
- a credentials object passed back to the application in request.auth.credentials
.artifacts
- optional authentication related data that is not part of the user's credential.
options
- (optional)
accessTokenName
(Default: 'access_token'
) - Rename token key e.g. 'new_name' would rename the token query parameter to /route1?new_name=1234
.allowQueryToken
(Default: false
) - Accept token via query parameter.allowCookieToken
(Default: false
) - Accept token via cookie.allowMultipleHeaders
(Default: false
) - Accept multiple authorization headers, e.g. Authorization: FD AF6C74D1-BBB2-4171-8EE3-7BE9356EB018; Bearer 12345678
.tokenType
(Default: 'Bearer'
) - Accept a custom token type e.g. Authorization: Basic 12345678
.allowChaining
(Default: false
) - Allow attempt of additional authentication strategies.unauthorized
(Default: Boom.unauthorized
) - A function to call when unauthorized with signature function([message], [scheme], [attributes])
. More details
const Hapi = require('hapi');
const AuthBearer = require('hapi-auth-bearer-token');
const server = Hapi.server({ port: 8080 });
const start = async () => {
await server.register(AuthBearer)
server.auth.strategy('simple', 'bearer-access-token', {
allowQueryToken: true,
validate: async (request, token, h) => {
const isValid = token === '1234';
const credentials = { token };
const artifacts = { test: 'info' };
return { isValid, credentials, artifacts };
}
});
server.auth.default('simple');
server.route({
method: 'GET',
path: '/',
handler: async function (request, h) {
return { info: 'success!' };
}
});
await server.start();
return server;
}
start()
.then((server) => console.log(`Server listening on ${server.info.uri}`))
.catch(err => {
console.error(err);
process.exit(1);
})
License MIT @ John Brett and other contributors 2017