View Source Joken (Joken v2.6.2)

Joken is a library for working with standard JSON Web Tokens.

It provides 4 basic operations:

  • Verify: the act of confirming the signature of the JWT;
  • Validate: processing validation logic on the set of claims;
  • Claim generation: generate dynamic value at token creation time;
  • Signature creation: encoding header and claims and generate a signature of their value.

Architecture

The core of Joken is JOSE, a library which provides all facilities to sign and verify tokens. Joken brings an easier Elixir API with some added functionality:

  • Validating claims. JOSE does not provide validation other than signature verification.
  • config.exs friendly. You can optionally define your signer configuration straight in your config.exs.
  • Portable configuration. All your token logic can be encapsulated in a module with behaviours.
  • Enhanced errors. Joken strives to be as informative as it can when errors happen be it at compilation or at validation time.
  • Debug friendly. When a token fails validation, a Logger debug message will show which claim failed validation with which value. The return value, though for security reasons, does not contain these information.
  • Performance. We have a benchmark suite for identifying where we can have a better performance. From this analysis came: Jason adapter for JOSE and other minor tweaks.

Usage

Joken has 3 basic concepts:

  • Portable token claims configuration.
  • Signer configuration.
  • Hooks.

The portable token claims configuration is a map of binary keys to Joken.Claim structs and is used to dynamically generate and validate tokens.

A signer is an instance of Joken.Signer that encapsulates the algorithm and the key configuration used to sign and verify a token.

A hook is an implementation of the behaviour Joken.Hooks for easy plugging into the lifecycle of Joken operations.

There are 2 forms of using Joken:

  1. Pure data structures. You can create your token configuration and signer and use them with this module for all 4 operations: verify, validate, generate and sign.

    iex> token_config = %{} # empty config
    iex> token_config = Map.put(token_config, "scope", %Joken.Claim{
    ...>   generate: fn -> "user" end,
    ...>   validate: fn val, _claims, _context -> val in ["user", "admin"] end
    ...> })
    iex> signer = Joken.Signer.create("HS256", "my secret")
    iex> {:ok, claims} = Joken.generate_claims(token_config, %{"extra"=> "claim"})
    iex> {:ok, jwt, claims} = Joken.encode_and_sign(claims, signer)
  2. With the encapsulated module approach using Joken.Config. See the docs for Joken.Config for more details.

    iex> defmodule MyAppToken do
    ...>   use Joken.Config, default_signer: :pem_rs256
    ...>
    ...>   @impl Joken.Config
    ...>   def token_config do
    ...>     default_claims()
    ...>     |> add_claim("role", fn -> "USER" end, &(&1 in ["ADMIN", "USER"]))
    ...>   end
    ...> end
    iex> {:ok, token, _claims} = MyAppToken.generate_and_sign(%{"user_id" => "1234567890"})
    iex> {:ok, _claim_map} = MyAppToken.verify_and_validate(token)

Summary

Types

A binary representing a bearer token.

A map with binary keys that represents a claim set.

Error reason which might contain dynamic data for helping understand the cause.

A list of hooks. Can be either a list of modules or a list of tuples with modules options to pass.

A signer argument that can be a key in the configuration or an instance of Joken.Signer.

A portable configuration of claims for generation and validation.

Functions

Retrieves current time in seconds.

Encodes and generates a token from the given claim map and signs the result with the given signer.

Expands a signed token into its 3 parts: protected, payload and signature.

Generates claims with the given token configuration and merges them with the given extra claims.

Default function for generating jti claims. This was inspired by the Plug.RequestId generation. It avoids using strong_rand_bytes as it is known to have some contention when running with many schedulers.

Decodes the claim set of a token without validation.

Decodes the header of a token without validation.

Validates the claim map with the given token configuration and the context.

Verifies a bearer_token using the given signer and executes hooks if any are given.

Types

@type bearer_token() :: binary()

A binary representing a bearer token.

@type claims() :: %{required(binary()) => term()}

A map with binary keys that represents a claim set.

@type error_reason() :: atom() | Keyword.t()

Error reason which might contain dynamic data for helping understand the cause.

@type generate_result() :: {:ok, claims()} | {:error, error_reason()}
@type hooks() :: [module()] | [{module(), any()}]

A list of hooks. Can be either a list of modules or a list of tuples with modules options to pass.

@type sign_result() :: {:ok, bearer_token(), claims()} | {:error, error_reason()}
@type signer_arg() :: atom() | Joken.Signer.t() | nil

A signer argument that can be a key in the configuration or an instance of Joken.Signer.

@type token_config() :: %{required(binary()) => Joken.Claim.t()}

A portable configuration of claims for generation and validation.

@type validate_result() :: {:ok, claims()} | {:error, error_reason()}
@type verify_result() :: {:ok, claims()} | {:error, error_reason()}

Functions

@spec current_time() :: pos_integer()

Retrieves current time in seconds.

This implementation uses an adapter so that you can replace it on your tests. The adapter is set through config.exs. Example:

config :joken,
  current_time_adapter: Joken.CurrentTime.OS

See Joken's own tests for an example of how to override this with a customizable time mock.

Link to this function

encode_and_sign(claims, signer, hooks \\ [])

View Source
@spec encode_and_sign(claims(), signer_arg(), hooks()) :: sign_result()

Encodes and generates a token from the given claim map and signs the result with the given signer.

It also executes hooks if any are given.

Expands a signed token into its 3 parts: protected, payload and signature.

Protected is also called the JOSE header. It contains metadata only like:

  • typ: the token type.
  • kid: an id for the key used in the signing.
  • alg: the algorithm used to sign a token.

Payload is the set of claims and signature is, well, the signature.

Link to this function

generate_and_sign(token_config, extra_claims \\ %{}, signer_arg \\ :default_signer, hooks \\ [])

View Source
@spec generate_and_sign(token_config(), claims(), signer_arg(), hooks()) ::
  {:ok, bearer_token(), claims()} | {:error, error_reason()}

Combines generate_claims/3 with encode_and_sign/3

Link to this function

generate_and_sign!(token_config, extra_claims \\ %{}, signer_arg \\ :default_signer, hooks \\ [])

View Source
@spec generate_and_sign!(token_config(), claims(), signer_arg(), hooks()) ::
  bearer_token()

Same as generate_and_sign/4 but raises if result is an error

Link to this function

generate_claims(token_config, extra \\ %{}, hooks \\ [])

View Source
@spec generate_claims(token_config(), claims() | nil, hooks()) :: generate_result()

Generates claims with the given token configuration and merges them with the given extra claims.

It also executes hooks if any are given.

@spec generate_jti() :: binary()

Default function for generating jti claims. This was inspired by the Plug.RequestId generation. It avoids using strong_rand_bytes as it is known to have some contention when running with many schedulers.

@spec peek_claims(bearer_token()) :: {:ok, claims()} | {:error, error_reason()}

Decodes the claim set of a token without validation.

Use this with care! This DOES NOT validate the token signature and therefore the token might be invalid. The common use case for this function is when you need info to decide on which signer will be used. Even though there is a use case for this, be extra careful to handle data without validation.

@spec peek_header(bearer_token()) :: {:ok, claims()} | {:error, error_reason()}

Decodes the header of a token without validation.

Use this with care! This DOES NOT validate the token signature and therefore the token might be invalid. The common use case for this function is when you need info to decide on which signer will be used. Even though there is a use case for this, be extra careful to handle data without validation.

Link to this function

validate(token_config, claims_map, context \\ nil, hooks \\ [])

View Source
@spec validate(token_config(), claims(), term(), hooks()) :: validate_result()

Validates the claim map with the given token configuration and the context.

Context can by any term. It is always passed as the second argument to the validate function. It can be, for example, a user struct or anything.

It also executes hooks if any are given.

Link to this function

verify(bearer_token, signer, hooks \\ [])

View Source
@spec verify(bearer_token(), signer_arg(), hooks()) :: verify_result()

Verifies a bearer_token using the given signer and executes hooks if any are given.

Link to this function

verify_and_validate(token_config, bearer_token, signer \\ :default_signer, context \\ nil, hooks \\ [])

View Source
@spec verify_and_validate(
  token_config(),
  bearer_token(),
  signer_arg(),
  term(),
  hooks()
) ::
  {:ok, claims()} | {:error, error_reason()}

Combines verify/3 and validate/4 operations

Link to this function

verify_and_validate!(token_config, bearer_token, signer \\ :default_signer, context \\ nil, hooks \\ [])

View Source
@spec verify_and_validate!(
  token_config(),
  bearer_token(),
  signer_arg(),
  term(),
  hooks()
) :: claims()

Same as verify_and_validate/5 but raises on error