A Session based auth scheme for Hapi
This scheme is based on hapi-session but the API is a bit diffrent (mostly using async and callback scheme) and most of the underline code has changed. As with the original scheme a lot of the code was gratuitously stolen from the hapi auth cookie scheme, and this module works in much the same way.
This Module will save a cookie with a unique session ID, the ID has high entropy and is randomly secure so it should be impossible to fake. all other data is never sent to the user so you can save in the session whatever information you wont without the fear of it being faked or compromised.
For Hapi 16.x and lower see previous version For demo server example usage see the server.js
await server.register({plugin: require('hapi-sol')});
server.auth.strategy('session', 'session', {/* Options Object*/});
server.auth.default('session');
After validating the user credentials saving them to the cookie is done by the session.set method
await request.auth.session.set({'logined': true, 'userid': 1});
return h.response('You are being redirected...').takeover().redirect('/');
notice this method is asynchronous. once the user is logged in you will have the credentials passed to the set method available in future connections at -
console.log(request.auth.credentials); //{'logined': true, 'userid': 1}
To logout the user you can either call set with null value or call the clear method
await request.auth.session.set(null);
return h.response('You are being redirected...').takeover().redirect('/');
//
await request.auth.session.clear();
return h.response('You are being redirected...').takeover().redirect('/');
the clear
method will completely remove the session from cache and create a new one while the set
method will leave the current session active but unauthenticated. As with the set
method clear
is asynchronous.
request.auth.session.getId
returns the current session ID
request.auth.session.getSeesion
returns the current session object
request.auth.session.setSeesion(session)
save session
as the current session object
since clients will always have an active persistent session it can be useful to attach some extra data to the session object
//on failed login attempt
const session = await request.auth.session.getSession();
session.attempts = session.attempts ? session.attempts + 1: 1;
await request.auth.session.setSession(session);
if (session.attempts > 5) {
//block user ip
}
Notice that the session
Object has two internally used properties
authenticated
Boolean is the true if the session has credentials associated with it.
credentials
Object credentials saved with the session
it better to avoid doing manual changes to this values (use the set
method instead) since setSession
will not do any validations on your session Object.
when setting an auth strategy you can set the following options:
cookie
The cookie name default('sid')sessionCookie
use browser session cookies (will only applyttl
settings for built in cache)path
The cookie path default('/'')ttl
Cookie and cache TTL in milliseconds default(1000 * 60 * 60 * 24 //one day)isHttpOnly
Set HTTP only cookie flag default(true)isSecure
Force SSL for cookie default(true)secret
Secret to be used to create local HMAC of the cookie id can help reduce timing attacks and using stolen cookies default(null)hmacAlgo
HMAC algorithm to be used (only used ifsecret
is set) default(sha1)_hmacEncoding
HMAC encoding (only used ifsecret
is set) default(base64)_hmacRequest
Array of values to be taken from the request that will be included in the HMAC make session harder to steal(only used ifsecret
is set) default(['info.remoteAddress', 'headers.user-agent'])_rlClient
rate limiting client to use for rate limiting users who try to bruteforce session ids. you can use ralphi-client or any object which implementsquery
andtake
methods.rlBucket
bucket to use for rate limiting default('session')rlGetKey
function/async for getting the rate limiting key from the request default(request => request.info.remoteAddress)rlAddHeaders
add rate limiting headers to limited responses default(true)cacheId
the cache ID to use when saving sessions default('_hapi_session')cache
caching manager if you want to use your own storage (needs to implement get,set and drop methods) default(undefined)validateFunc
Async function to farther validate the cookie if needed function signature should be (request, credentials) function should return an array first item is boolean value indicating if credentials are valid, and optional second value can be returned with an object of a parsed credentials to replace the credentials being set in the authentication process default(undefined)clearInvalid
If cookie is tested to be invalid by the validateFunc should we clear the existing cookie default(true)sidLength
The length in Bytes for the generated random ID Should be high enough so collision would be impossible minimum 10 bytes default(16)uidRetries
How many retries should be made to generate the ID (in case of missing entropy) default(5)redirectTo
Location to redirect to in case of auth Error default(''//Empty string)appendNext
if truthy will add a query parameter with the same name in the redirection url back to the current route boolean true will set the name 'next' default(''//Empty string)redirectOnTry
if mode is set to try and auth fails redirect the request default(false)