hapi-auth-cookie
hapi Cookie authentication plugin
Lead Maintainer: Eran Hammer
Cookie authentication provides simple cookie-based session management. The user has to be authenticated via other means, typically a web form, and upon successful authentication the browser receives a reply with a session cookie. The cookie uses Iron to encrypt and sign the session content.
Subsequent requests containing the session cookie are authenticated and validated via the provided validateFunc
in case the cookie's encrypted content requires validation on each request.
It is important to remember a couple of things:
- Each cookie operates as a bearer token and anyone in possession of the cookie content can use it to impersonate its true owner.
- Cookies have a practical maximum length. All of the data you store in a cookie is sent to the browser. If your cookie is too long, browsers may not set it. Read more here and here. If you need to store more data, store a small amount of identifying data in the cookie and use that as a key to a server-side cache system.
The 'cookie
' scheme takes the following options:
-
cookie
- an object with the following:name
- the cookie name. Defaults to'sid'
.password
- used for Iron cookie encoding. Should be at least 32 characters long.ttl
- sets the cookie expires time in milliseconds. Defaults to single browser session (ends when browser closes). Required whenkeepAlive
istrue
.domain
- sets the cookie Domain value. Defaults to none.path
- sets the cookie path value. Defaults to none.clearInvalid
- iftrue
, any authentication cookie that fails validation will be marked as expired in the response and cleared. Defaults tofalse
.isSameSite
- iffalse
omitted. Other optionsStrict
orLax
. Defaults toStrict
.isSecure
- iffalse
, the cookie is allowed to be transmitted over insecure connections which exposes it to attacks. Defaults totrue
.isHttpOnly
- iffalse
, the cookie will not include the 'HttpOnly' flag. Defaults totrue
.
-
keepAlive
- iftrue
, automatically sets the session cookie after validation to extend the current session for a newttl
duration. Defaults tofalse
. -
redirectTo
- optional login URI or functionfunction(request)
that returns a URI to redirect unauthenticated requests to. Note that it will only trigger when the authentication mode is'required'
. To enable or disable redirections for a specific route, set the routeplugins
config ({ options: { plugins: { 'hapi-auth-cookie': { redirectTo: false } } } }
). Defaults to no redirection. -
appendNext
- ifredirectTo
istrue
, can be a boolean, string, or object. Defaults tofalse
.- if set to
true
, a string, or an object, appends the current request path to the query component of theredirectTo
URI - set to a string value or set the
name
property in an object to define the parameter name. defaults to'next'
- set the
raw
property of the object totrue
to determine the current request path based on the raw node.js request object received from the HTTP server callback instead of the processed hapi request object
- if set to
-
async validateFunc
- an optional session validation function used to validate the content of the session cookie on each request. Used to verify that the internal session state is still valid (e.g. user account still exists). The function has the signaturefunction(request, session)
where:request
- is the Hapi request object of the request which is being authenticated.session
- is the session object set viarequest.cookieAuth.set()
.
Must return an object that contains:
valid
-true
if the content of the session is valid, otherwisefalse
.credentials
- a credentials object passed back to the application inrequest.auth.credentials
. If value isnull
orundefined
, defaults tosession
. If set, will override the current cookie as ifrequest.cookieAuth.set()
was called.
-
requestDecoratorName
- USE WITH CAUTION an optional name to use with decorating therequest
object. Defaults to'cookieAuth'
. Using multiple decorator names for separate authentication strategies could allow a developer to call the methods for the wrong strategy. Potentially resulting in unintended authorized access.
When the cookie scheme is enabled on a route, the request.cookieAuth
objects is decorated with
the following methods:
set(session)
- sets the current session. Must be called after a successful login to begin the session.session
must be a non-null object, which is set on successful subsequent authentications inrequest.auth.credentials
where:session
- the session object.
set(key, value)
- sets a specific object key on the current session (which must already exist) where:key
- session key string.value
- value to assign key.
clear([key])
- clears the current session or session key where:key
- optional key string to remove a specific property of the session. If none provided, defaults to removing the entire session which is used to log the user out.
ttl(msecs)
- sets the ttl of the current active session where:msecs
- the new ttl in milliseconds.
Because this scheme decorates the request
object with session-specific methods, it cannot be
registered more than once.
'use strict'; const Hapi = ; const internals = {}; // Simulate database for demo internalsusers = id: 1 name: 'john' password: 'password' ; internalsrenderHtml = { return ` <html><head><title>Login page</title></head><body> <form method="post" action="/login"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br/> <input type="submit" value="Login"></form> </body></html> `; } { return ` <html><head><title>Login page</title></head><body> <h3>Welcome ! You are logged in!</h3> <form method="get" action="/logout"> <input type="submit" value="Logout"> </form> </body></html> `; }; internals { const server = Hapi; await server; serverauth; serverauth; server; await serverstart; console;}; internals { try await internals; catch err console; process; }; internalsstart;