Joken.Plug

A Plug for signing and verifying authentication tokens.

Usage

There are two possible scenarios:

  1. Same configuration for all routes
  2. Per route configuration

In the first scenario just add this plug before the dispatch plug.

defmodule MyRouter do
  use Plug.Router

  plug Joken.Plug, on_verifying: &verify_function/1
  plug :match
  plug :dispatch

  post "/user" do
    # will only execute here if token is present and valid
  end

  match _ do
    # will only execute here if token is present and valid
  end
end

In the second scenario, you will need at least plug ~> 0.14 in your deps. Then you must plug this AFTER :match and BEFORE :dispatch.

defmodule MyRouter do
  use Plug.Router

  # route options
  @skip_token_verification %{joken_skip: true}

  plug :match
  plug Joken.Plug, config_module: MyJWTConfig        
  plug :dispatch

  post "/user" do
    # will only execute here if token is present and valid
  end

  # see options section below
  match _, private: @skip_token_verification do
    # will NOT try to validate a token
  end
end

Options

This plug accepts the following options in its initialization:

  • on_verifying: a function used to verify the token. Receives a Token and must return a Token

  • on_error (optional): a function that will be called with conn and message. Must return a tuple containing the conn and a binary representing the 401 response. If it’s a map, it will be turned into json, otherwise, it will be returned as is.

When using this with per route options you must pass a private map of options to the route. The keys that Joken will look for in that map are:

  • joken_skip: skips token validation

  • joken_on_verifying: Same as on_verifying above. Overrides on_verifying if it was defined on the Plug

  • joken_on_error: Same as on_error above. Overrides on_error if it was defined on the Plug