/phoenix_token_plug

Collection of plugs for Phoenix.Token-based authentication

Primary LanguageElixirMIT LicenseMIT

PhoenixTokenPlug

Collection of plugs for Phoenix.Token-based authentication. Useful for authenticating API calls.

Heavily inspired by Guardian.

Why?

In building APIs with Phoenix, often we need to have authentication mechanisms. Some of the prevalent solution is Guardian.

However, Guardian uses JWT as its main currency. While not bad in itself, Phoenix already provides token signing and verification mechanism through Phoenix.Token, which is a lightweight alternative to JWT. For comparison of Phoenix.Token and JWT, see here and here.

This library kind of mirrors a part of what Guardian does except that it uses Phoenix.Token.

Installation

Add phoenix_token_plug to your list of dependencies in mix.exs:

def deps do
  [{:phoenix_token_plug, "~> 0.2"}]
end

Usage

Add the plugs to your router (or one of your pipelines):

defmodule MyApp.Router do
  # ...

  pipeline :api do
    plug :accepts, ["json"]

    # Checks for Authorization: Bearer <token> header, and adds
    # the token payload to conn.assigns.user if token exists
    plug PhoenixTokenPlug.VerifyHeader,
      salt: "user",
      max_age: 1_209_600
  end

  pipeline :protected do
    # Checks if conn.assigns.user exists; if not, will
    # call MyApp.AuthController.unauthenticated/2
    plug PhoenixTokenPlug.EnsureAuthenticated,
      handler: MyApp.AuthController # Or any other module
  end

  scope "/api", MyApp do
    pipe_through [:api, :protected]

    get "/protected", IndexController, :protected_route
  end

  # ...
end

And implement unauthenticated/2:

defmodule MyApp.AuthController do
  # ...

  def unauthenticated(conn, _params) do
    conn
    |> put_status(401)
    |> json(%{error: "Unauthenticated!"})
  end

  # ...
end

For further customization options, please consult the docs.