Authex.Plug.Authentication (Authex v2.2.0) View Source

A plug to handle authentication.

This plug must be passed an auth module in which to authenticate with. Otherwise, it will raise an Authex.Error.

With it, we can easily authenticate a Phoenix controller:

defmodule MyAppWeb.MyController do
  use MyAppWeb, :controller

  plug Authex.Plug.Authentication, with: MyApp.Auth

  def show(conn, _params) do
    with {:ok, %{id: id}} <- MyApp.Auth.current_user(conn),
        {:ok, user} <- MyApp.Users.get(id)
    do
      render(conn, "show.json", user: user)
    end
  end
end

The plug looks for the Authorization: Bearer mytoken header by default. It will then verify and covert out token into a resource using the provided auth module.

We can then access our current resource from the conn using Authex.current_resource/1.

By default, if authentication fails, the plug sends the conn to the Authex.Plug.Unauthorized plug. This plug will put a 401 status into the conn with the body "Unauthorized". We can configure our own unauthorized plug by passing it as an option to this plug.

Options

  • :with - The auth module that will be used for verification and token conversion.
  • :unauthorized - The plug to call when the token is invalid - defaults to Authex.Plug.Unauthorized.
  • :header - The header to extract the token from - defaults to "authorization".

Link to this section Summary

Link to this section Types

Specs

option() ::
  {:with, Authex.t()} | {:unauthorized, module()} | {:header, binary()}

Specs

options() :: [option()]