Module resty.session

Session library.

Session library provides HTTP session management capabilities for OpenResty based applications, libraries and proxies.

Session

instance.info:set (key, value) Set a value in session information store.
instance.info:get (key) Get a value from session information store.
instance.info:save () Save information.
instance:set_data (data) Set session data.
instance:get_data () Get session data.
instance:set (key, value) Set a value in session.
instance:get (key) Get a value from session.
instance:set_audience (audience) Set session audience.
instance:get_audience () Get session audience.
instance:set_subject (subject) Set session subject.
instance:get_subject () Get session subject.
instance:get_property () Get session property.
instance:set_remember (value) Set persistent sessions on/off.
instance:get_remember () Get state of persistent sessions.
instance:open () Open a session.
instance:save () Save the session.
instance:touch () Touch the session.
instance:refresh () Refresh the session.
instance:logout () Logout the session.
instance:destroy () Destroy the session.
instance:close () Close the session.
instance:clear_request_cookie () Clear the request session cookie.
instance:set_headers ([...]) Sets request and response headers.
instance:set_request_headers ([...]) Set request headers.
instance:set_response_headers ([...]) Set response headers.

Configuration

configuration Session configuration.

Initialization

module.init ([configuration]) Initialize the session library.

Constructors

module.new ([configuration]) Create a new session.

Helpers

module.open ([configuration]) Open a session.
module.start ([configuration]) Start a session and refresh it as needed.
module.logout ([configuration]) Logout a session.
module.destroy ([configuration]) Destroy a session.


Session

instance.info:set (key, value)
Set a value in session information store.

Parameters:

instance.info:get (key)
Get a value from session information store.

Parameters:

Returns:

    value
instance.info:save ()
Save information.

Only updates backend storage. Does not send a new cookie.

Returns:

  1. true or nil ok
  2. string error message
instance:set_data (data)
Set session data.

Parameters:

Usage:

    local session, err, exists = require "resty.session".open()
    if not exists then
      session:set_data({
        cart = {},
      })
      session:save()
    end
instance:get_data ()
Get session data.

Returns:

    table value

Usage:

    local session, err, exists = require "resty.session".open()
    if exists then
      local data = session:get_data()
      ngx.req.set_header("Authorization", "Bearer " .. data.access_token)
    end
instance:set (key, value)
Set a value in session.

Parameters:

  • key string key
  • value value

    local session, err, exists = require “resty.session”.open() if not exists then session:set(“access-token”, “eyJ…”) session:save() end

instance:get (key)
Get a value from session.

Parameters:

Returns:

    value

Usage:

    local session, err, exists = require "resty.session".open()
    if exists then
      local access_token = session:get("access-token")
      ngx.req.set_header("Authorization", "Bearer " .. access_token)
    end
instance:set_audience (audience)
Set session audience.

Parameters:

Usage:

    local session = require "resty.session".new()
    session.set_audience("my-service")
instance:get_audience ()
Get session audience.

Returns:

    string audience
instance:set_subject (subject)
Set session subject.

Parameters:

Usage:

    local session = require "resty.session".new()
    session.set_subject("john@doe.com")
instance:get_subject ()
Get session subject.

Returns:

    string subject

Usage:

    local session, err, exists = require "resty.session".open()
    if exists then
      local subject = session.get_subject()
    end
instance:get_property ()
Get session property.

Possible property names: "id": 43 bytes session id (same as nonce, but base64 url-encoded) "nonce": 32 bytes nonce (same as session id but in raw bytes) "audience": Current session audience "subject": Current session subject "timeout": Closest timeout (in seconds) (what’s left of it) "idling-timeout: Session idling timeout (in seconds) (what's left of it) "rolling-timeout": Session rolling timeout (in seconds) (what’s left of it) "absolute-timeout: Session absolute timeout (in seconds) (what's left of it)

Returns:

    string or number metadata

Usage:

    local session, err, exists = require "resty.session".open()
    if exists then
      local timeout = session.get_property("timeout")
    end
instance:set_remember (value)
Set persistent sessions on/off.

In many login forms user is given an option for “remember me”. You can call this function based on what user selected.

Parameters:

  • value boolean true to enable persistent session, false to disable them
instance:get_remember ()
Get state of persistent sessions.

Returns:

    boolean true when persistent sessions are enabled, otherwise false
instance:open ()
Open a session.

This can be used to open a session.

Returns:

  1. true or nil ok
  2. string error message
instance:save ()
Save the session.

Saves the session data and issues a new session cookie with a new session id. When remember is enabled, it will also issue a new persistent cookie and possibly save the data in backend store.

Returns:

  1. true or nil ok
  2. string error message
instance:touch ()
Touch the session.

Updates idling offset of the session by sending an updated session cookie. It only sends the client cookie and never calls any backend session store APIs. Normally the session:refresh is used to call this indirectly.

Returns:

  1. true or nil ok
  2. string error message
instance:refresh ()
Refresh the session.

Either saves the session (creating a new session id) or touches the session depending on whether the rolling timeout is getting closer, which means by default when ¾ of rolling timeout is spent – 45 minutes with default rolling timeout of an hour. The touch has a threshold, by default one minute, so it may be skipped in some cases (you can call session:touch() to force it).

Returns:

  1. true or nil ok
  2. string error message
instance:logout ()
Logout the session.

Logout either destroys the session or just clears the data for the current audience, and saves it (logging out from the current audience).

Returns:

  1. true or nil ok
  2. string error message
instance:destroy ()
Destroy the session.

Destroy the session and clear the cookies.

Returns:

  1. true or nil ok
  2. string error message
instance:close ()
Close the session.

Just closes the session instance so that it cannot be used anymore.

instance:clear_request_cookie ()
Clear the request session cookie.

Modifies the request headers by removing the session related cookies. This is useful when you use the session library on a proxy server and don’t want the session cookies to be forwarded to the upstream service.

instance:set_headers ([...])
Sets request and response headers.

Parameters:

instance:set_request_headers ([...])
Set request headers.

Parameters:

instance:set_response_headers ([...])
Set response headers.

Parameters:

Configuration

configuration
Session configuration.

Fields:

  • secret Secret used for the key derivation. The secret is hashed with SHA-256 before using it. E.g. "RaJKp8UQW1".
  • secret_fallbacks Array of secrets that can be used as alternative secrets (when doing key rotation), E.g. { "6RfrAYYzYq", "MkbTkkyF9C" }.
  • ikm Initial key material (or ikm) can be specified directly (without using a secret) with exactly 32 bytes of data. E.g. "5ixIW4QVMk0dPtoIhn41Eh1I9enP2060"
  • ikm_fallbacks Array of initial key materials that can be used as alternative keys (when doing key rotation), E.g. { "QvPtlPKxOKdP5MCu1oI3lOEXIVuDckp7" }.
  • cookie_prefix Cookie prefix, use nil, "__Host-" or "__Secure-" (defaults to nil)
  • cookie_name Session cookie name, e.g. "session" (defaults to "session")
  • cookie_path Cookie path, e.g. "/" (defaults to "/")
  • cookie_domain Cookie domain, e.g. "example.com" (defaults to nil)
  • cookie_http_only Mark cookie HTTP only, use true or false (defaults to true)
  • cookie_secure Mark cookie secure, use nil, true or false (defaults to nil)
  • cookie_priority Cookie priority, use nil, "Low", "Medium", or "High" (defaults to nil)
  • cookie_same_site Cookie same-site policy, use nil, "Lax", "Strict", "None", or "Default" (defaults to "Lax")
  • cookie_same_party Mark cookie with same party flag, use nil, true, or false (default: nil)
  • cookie_partitioned Mark cookie with partitioned flag, use nil, true, or false (default: nil)
  • remember Enable or disable persistent sessions, use nil, true, or false (defaults to false)
  • remember_safety Remember cookie key derivation complexity, use nil, "None" (fast), "Low", "Medium", "High" or "Very High" (slow) (defaults to "Medium")
  • remember_cookie_name Persistent session cookie name, e.g. "remember" (defaults to "remember")
  • audience Session audience, e.g. "my-application" (defaults to "default")
  • subject Session subject, e.g. "john.doe@example.com" (defaults to nil)
  • enforce_same_subject When set to true, audiences need to share the same subject. The library removes non-subject matching audience data on save.
  • stale_ttl When session is saved a new session is created, stale ttl specifies how long the old one can still be used, e.g. 10 (defaults to 10) (in seconds)
  • idling_timeout Idling timeout specifies how long the session can be inactive until it is considered invalid, e.g. 900 (defaults to 900, or 15 minutes) (in seconds)
  • rolling_timeout Rolling timeout specifies how long the session can be used until it needs to be renewed, e.g. 3600 (defaults to 3600, or an hour) (in seconds)
  • absolute_timeout Absolute timeout limits how long the session can be renewed, until re-authentication is required, e.g. 86400 (defaults to 86400, or a day) (in seconds)
  • remember_rolling_timeout Remember timeout specifies how long the persistent session is considered valid, e.g. 604800 (defaults to 604800, or a week) (in seconds)
  • remember_absolute_timeout Remember absolute timeout limits how long the persistent session can be renewed, until re-authentication is required, e.g. 2592000 (defaults to 2592000, or 30 days) (in seconds)
  • hash_storage_key Whether to hash or not the storage key. With storage key hashed it is impossible to decrypt data on server side without having a cookie too (defaults to false).
  • hash_subject Whether to hash or not the subject when store_metadata is enabled, e.g. for PII reasons (defaults to false).
  • store_metadata Whether to also store metadata of sessions, such as collecting data of sessions for a specific audience belonging to a specific subject (defaults to false).
  • touch_threshold Touch threshold controls how frequently or infrequently the session:refresh touches the cookie, e.g. 60 (defaults to 60, or a minute) (in seconds)
  • compression_threshold Compression threshold controls when the data is deflated, e.g. 1024 (defaults to 1024, or a kilobyte) (in bytes)
  • request_headers Set of headers to send to upstream, use id, audience, subject, timeout, idling-timeout, rolling-timeout, absolute-timeout. E.g. { "id", "timeout" } will set Session-Id and Session-Timeout request headers when set_headers is called.
  • response_headers Set of headers to send to downstream, use id, audience, subject, timeout, idling-timeout, rolling-timeout, absolute-timeout. E.g. { "id", "timeout" } will set Session-Id and Session-Timeout response headers when set_headers is called.
  • storage Storage is responsible of storing session data, use nil or "cookie" (data is stored in cookie), "dshm", "file", "memcached", "mysql", "postgres", "redis", or "shm", or give a name of custom module ("custom-storage"), or a table that implements session storage interface (defaults to nil)
  • dshm Configuration for dshm storage, e.g. { prefix = "sessions" }
  • file Configuration for file storage, e.g. { path = "/tmp", suffix = "session" }
  • memcached Configuration for memcached storage, e.g. { prefix = "sessions" }
  • mysql Configuration for MySQL / MariaDB storage, e.g. { database = "sessions" }
  • postgres Configuration for Postgres storage, e.g. { database = "sessions" }
  • redis Configuration for Redis / Redis Sentinel / Redis Cluster storages, e.g. { prefix = "sessions" }
  • shm Configuration for shared memory storage, e.g. { zone = "sessions" }
  • custom -storage"] Custom storage (loaded with require "custom-storage") configuration

Initialization

module.init ([configuration])
Initialize the session library.

This function can be called on init or init_worker phases on OpenResty to set global default configuration to all session instances created by this library.

Parameters:

Usage:

    require "resty.session".init({
      audience = "my-application",
      storage = "redis",
      redis = {
        username = "session",
        password = "storage",
      },
    })

Constructors

module.new ([configuration])
Create a new session.

This creates a new session instance.

Parameters:

Returns:

    table session instance

Usage:

    local session = require "resty.session".new()
    -- OR
    local session = require "resty.session".new({
      audience = "my-application",
    })

Helpers

module.open ([configuration])
Open a session.

This can be used to open a session, and it will either return an existing session or a new session.

Parameters:

Returns:

  1. table session instance
  2. string error message
  3. boolean true, if session existed, otherwise false

Usage:

    local session = require "resty.session".open()
    -- OR
    local session, err, exists = require "resty.session".open({
      audience = "my-application",
    })
module.start ([configuration])
Start a session and refresh it as needed.

This can be used to start a session, and it will either return an existing session or a new session. In case there is an existing session, the session will be refreshed as well (as needed).

Parameters:

Returns:

  1. table session instance
  2. string error message
  3. boolean true, if session existed, otherwise false
  4. boolean true, if session was refreshed, otherwise false

Usage:

    local session = require "resty.session".start()
    -- OR
    local session, err, exists, refreshed = require "resty.session".start({
      audience = "my-application",
    })
module.logout ([configuration])
Logout a session.

It logouts from a specific audience.

A single session cookie may be shared between multiple audiences (or applications), thus there is a need to be able to logout from just a single audience while keeping the session for the other audiences.

When there is only a single audience, then this can be considered equal to session.destroy.

When the last audience is logged out, the cookie will be destroyed as well and invalidated on a client.

Parameters:

Returns:

  1. boolean true session exists for an audience and was logged out successfully, otherwise false
  2. string error message
  3. boolean true if session existed, otherwise false
  4. boolean true if session was logged out, otherwise false

Usage:

    require "resty.session".logout()
    -- OR
    local ok, err, exists, logged_out = require "resty.session".logout({
      audience = "my-application",
    })
module.destroy ([configuration])
Destroy a session.

It destroys the whole session and clears the cookies.

Parameters:

Returns:

  1. boolean true session exists and was destroyed successfully, otherwise nil
  2. string error message
  3. boolean true if session existed, otherwise false
  4. boolean true if session was destroyed, otherwise false

Usage:

    require "resty.session".destroy()
    -- OR
    local ok, err, exists, destroyed = require "resty.session".destroy({
      cookie_name = "auth",
    })
generated by LDoc 1.5.0 Last updated 2023-08-16 18:11:28