Hapi plugin to authenticate with signed links
About
This plugin provides the ability to use cryptographic signed links as authentication strategy in Hapi.
With this strategy enable on a route arequest with an ?auth=<signature> query parameter containing a valid signature value of the link is considered an authenticaed request.
When the url contains an expires_at=<millis since 1.1.1970> authentication fails when the links has expired.
Any link manipulation causes the signature to become invalid and hapi would by default return a 401 Unauthorized response. This behaviour can be overrwriten with the failAction option.
Compatiblity
hapi <= 17.0.0 => hapi-auth-signed-link <= 1.0.0
hapi >= 17.0.0 => hapi-auth-signed-link >= 1.0.0
hapi >= 21.0.0 => hapi-auth-signed-link >= 1.3.0
Usaage
Setup auth strategy and use it for a route
const hapiAuthSignedlink = require('@trigo/hapi-auth-signedlink')
server = new Hapi.Server();
await server.register(hapiAuthSignedlink);
server.auth.strategy('default', 'signedlink', {
key: 'super secret signing key',
failAction: async (request, h, reason) => h.redirect('http://www.domain/my-error-page').takeover()
});
server.route([
{
method: 'POST',
path: '/token',
handler: tokenHandler,
options: {
auth: 'default',
},
},
]);
Usage of failAction option
A custom failAction method may be registered in order to customize the behaviour in case of failing authentication.
failAction: async (request, h, reason) => h.redirect(`http://www.domain/my-error-page?reason=${encodeURIComponent(reason)}`).takeover()
The default bahaviour is to return a HTTP 401 Unauthorized error with
either one of the three possible error codes:
E_AUTH_PARAM_MISSING - the URL did not contain the required auth=<signature> query parameter
E_LINK_EXPIRED - the URL's expires_at=<timestamp> lies in the past
E_INVALID_SIGNATURE - the siganture does not validate. e.g. the link was modified or created with another signing key
The error code that occoured is passed to the failAction method as third parameter reason
Create a signed link
Whe installed a helper method to create links is available in all hanlders throught the request object: request.server.plugins.hapiAuthSignedLink.createLink(<link>)