@hapi/cookie Cookie Authentication Plugin

repository·master·Indexed 42 days ago

https://github.com/hapijs/cookie

A cookie authentication plugin for the hapi ecosystem used to manage cookie-based authentication and state. It provides a cookie authentication scheme and decorates the request object (defaulting to cookieAuth) to set, clear, and modify session data. Version 12.0.1 requires hapi >=20.0.0.

Tokens
1.4K
Snippets
3
Records
4
Agent score
3%

What's inside @hapi/cookie

  1. Overview of @hapi/cookie

    master
    @hapi/cookie is a cookie authentication plugin designed to work seamlessly with the hapi web framework. While optimized for the hapi ecosystem, it is a standalone module that can be used with other web frameworks.
  2. Register the @hapi/cookie plugin

    master

    To use cookie-based authentication in Hapi, register the @hapi/cookie plugin. This plugin sets up a cookie authentication scheme and decorates the request object with a decorator (defaulting to cookieAuth) to manage session state.

    Requirements:

    • hapi: >=20.0.0
    await server.register({
        plugin: require('@hapi/cookie'),
        options: {
            cookie: {
                name: 'sid',
                password: 'password-must-be-at-least-32-characters-long',
                encoding: 'iron'
            }
        }
    });
  3. Configure @hapi/cookie plugin options

    master

    When registering the plugin, you can provide an options object to configure cookie behavior.

    Defines the underlying Hapi state configuration.

    • name (String): The name of the cookie. Defaults to 'sid'.
    • password (String): The password used for encryption (required).
    • encoding (String): The encoding method. Defaults to 'iron'.
    • clearInvalid (Boolean): If true, the cookie is cleared if validation fails.

    validate (Function, Optional)

    A function used to validate the session data. It receives (request, session) and must return an object containing { isValid: boolean }. You can optionally return credentials to override the authenticated credentials.

    keepAlive (Boolean)

    If true, the cookie is re-set on every request to extend its life. This requires cookie.ttl to be set.

    redirectTo (String | Function | Boolean)

    Determines where to redirect the user if they are unauthenticated.

    • false: Returns an unauthenticated error.
    • String: A static URI.
    • Function: A function that receives the request and returns a URI.

    appendNext (String | Boolean | Object)

    If redirecting, this determines if the original URL is appended as a query parameter.

    • true: Appends ?next=...
    • false: Does not append.
    • Object: { raw: boolean, name: string }. If raw is true, it uses the raw request URL; otherwise, it uses the parsed pathname and search. name allows customizing the query parameter key.

    requestDecoratorName (String)

    The name of the decorator added to the request object. Defaults to 'cookieAuth'.

    {
        cookie: {
            name: 'sid',
            password: 'your-secret-password',
            encoding: 'iron'
        },
        validate: async (request, session) => {
            // validation logic
            return { isValid: true };
        },
        redirectTo: '/login',
        appendNext: 'returnTo'
    }
  4. Manage sessions with request.cookieAuth

    master

    The plugin decorates the request object with a method (defaulting to cookieAuth) to interact with the session cookie. This object provides methods to set, clear, and modify the session.

    set(session, value)

    Sets the session data.

    • Full Session: request.cookieAuth.set(sessionObject) sets the entire session and returns a state header. This updates request.auth.artifacts.
    • Key-Value: request.cookieAuth.set('key', 'value') updates a specific key within the existing session stored in request.auth.artifacts and returns a state header.

    clear(key)

    Removes a specific key from the session or clears the entire session.

    • Specific Key: request.cookieAuth.clear('key') deletes the key from the session and returns a state header.
    • Full Clear: request.cookieAuth.clear() sets request.auth.artifacts to null and unsets the cookie.

    ttl(msecs)

    Updates the Time-To-Live for the cookie in milliseconds.

    Note: These methods return a state header (via h.state) which must be returned by your handler to actually apply the changes to the response.

    // In a Hapi handler
    server.route({
        method: 'POST',
        path: '/login',
        handler: async (request, h) => {
            // Set the entire session
            const session = { userId: 123 };
            return request.cookieAuth.set(session);
        }
    });
    
    server.route({
        method: 'POST',
        path: '/update-profile',
        handler: async (request, h) => {
            // Update a specific key in the existing session
            return request.cookieAuth.set('theme', 'dark');
        }
    });
    
    server.route({
        method: 'POST',
        path: '/logout',
        handler: async (request, h) => {
            // Clear the entire session
            return request.cookieAuth.clear();
        }
    });