AshAuthentication.Strategy.ApiKey.Plug (ash_authentication v4.8.6)

View Source

Plug for authenticating using API keys.

This plug validates API keys from either a query parameter or HTTP header.

Summary

Functions

Process the connection and attempt to authenticate using the API key.

Initialize the plug with options.

Handles errors that occur during the api key authentication process.

Types

auth_error()

@type auth_error() :: :invalid_api_key | :missing_api_key | :authentication_failed

source_type()

@type source_type() :: :header | :query_param | :header_or_query_param

Functions

call(conn, config)

Process the connection and attempt to authenticate using the API key.

init(opts)

Initialize the plug with options.

Options

  • :resource - The resource to authenticate against.
  • :source - Where to get the API key from. Can be :header, :query_param or :header_or_query_param. Default: :header. Keep in mind that query params are often stored in logs etc, so we highly recommend using :header.
  • :param_name - The name of the query parameter when source: :query_param. Default: "api_key"
  • :header_prefix - The prefix to strip from the Authorization header value when source: :header. Default: "Bearer "
  • :strategy - The name of the API key strategy being used, defaults to the only api key strategy on the resource, or an error if there are multiple.
  • :required? - If true, the absence of an API key is treated as an error, and the on_error function is called with :missing_api_key. Default: true.
  • :on_error - The function to call when an error occurs. Takes a conn and an error which will be :invalid_api_key or an AshAuthentication error. The default is: AshAuthentication.Strategy.ApiKey.Plug.on_error/2
  • :assign - The name of the assign to set the authenticated subject. Default: :current_<subject>, i.e :current_user

on_error(conn, error)

Handles errors that occur during the api key authentication process.

This function determines the response format based on the Accept header of the incoming request. If the client accepts JSON responses, it returns a JSON-formatted error message. Otherwise, it returns a plain text error message.

  • If the Accept header contains "json", the response will be:
    • Status: 401 Unauthorized
    • Content-Type: application/json
    • Body: {"error":"Unauthorized"}
  • Otherwise, the response will be:
    • Status: 401 Unauthorized
    • Content-Type: text/plain (default)
    • Body: Unauthorized