Assent (Assent v0.3.1)

View Source

Multi-provider authentication framework.

Features

Usage

A strategy consists of two phases; request and callback. In the request phase, the user will be redirected to the auth provider for authentication and then returned to initiate the callback phase.

Single provider

This is an example using the Assent.Strategy.Github strategy with Plug:

defmodule GithubAuth do
  import Plug.Conn

  alias Assent.Strategy.Github

  defp config do
    [
      client_id: Application.fetch_env!(:my_app, :github, :client_id),
      client_secret: Application.fetch_env!(:my_app, :github, :client_secret),
      redirect_uri: "http://localhost:4000/auth/github/callback"
    ]
  end

  # http://localhost:4000/auth/github
  def request(conn) do
    config()
    |> Github.authorize_url()
    |> case do
      {:ok, %{url: url, session_params: session_params}} ->
        # Session params (used for OAuth 2.0 and OIDC strategies) will be
        # retrieved when user returns for the callback phase
        conn = put_session(conn, :session_params, session_params)

        # Redirect end-user to Github to authorize access to their account
        conn
        |> put_resp_header("location", url)
        |> send_resp(302, "")

      {:error, _error} ->
        # Something went wrong generating the request authorization url
        send_resp(conn, 500, "Failed authorization")
    end
  end

  # http://localhost:4000/auth/github/callback
  def callback(conn) do
    # End-user will return to the callback URL with params attached to the
    # request. These must be passed on to the strategy. In this example we only
    # expect GET query params, but the provider could also return the user with
    # a POST request where the params is in the POST body.
    %{params: params} = fetch_query_params(conn)

    # The session params (used for OAuth 2.0 and OIDC strategies) stored in the
    # request phase will be used in the callback phase
    session_params = get_session(conn, :session_params)

    conn = delete_session(conn, :session_params)

    config()
    # Session params should be added to the config so the strategy can use them
    |> Keyword.put(:session_params, session_params)
    |> Github.callback(params)
    |> case do
      {:ok, %{user: user, token: token}} ->
        # Authorization succesful
        conn
        |> put_session(:user, user)
        |> put_session(:token, token)
        |> put_resp_header("location", "/")
        |> send_resp(302, "")

      {:error, _error} ->
        # Authorizaiton failed
        send_resp(conn, 500, "Failed authorization")
    end
  end
end

Multi-provider

All assent strategies work the same way, so if you have more than one strategy you may want to set up a single module to handle any of the auth strategies. This example is a generalized flow that's similar to what's used in PowAssent.

config :my_app, :strategies,
  github: [
    client_id: "REPLACE_WITH_CLIENT_ID",
    client_secret: "REPLACE_WITH_CLIENT_SECRET",
    strategy: Assent.Strategy.Github
  ],
  # Other strategies
defmodule MultiProviderAuth do
  @spec authorize_url(atom()) :: {:ok, map()} | {:error, term()}
  def authorize_url(provider) do
    config = config!(provider)

    config[:strategy].authorize_url()
  end

  @spec callback(atom(), map(), map()) :: {:ok, map()} | {:error, term()}
  def callback(provider, params, session_params) do
    config = config!(provider)

    config
    |> Keyword.put(:session_params, session_params)
    |> config[:strategy].callback(params)
  end

  defp config!(provider) do
    config =
      Application.get_env(:my_app, :strategies)[provider] ||
        raise "No provider configuration for #{provider}"
    
    Keyword.put(config, :redirect_uri, "http://localhost:4000/oauth/#{provider}/callback")
  end
end

Custom provider

You can create custom strategies. Here's an example of an OAuth 2.0 implementation using Assent.Strategy.OAuth2.Base:

defmodule TestProvider do
  use Assent.Strategy.OAuth2.Base

  @impl true
  def default_config(_config) do
    [
      # `:base_url` will be used for any paths below
      base_url: "http://localhost:4000/api/v1",
       # Definining an absolute URI overrides the `:base_url`
      authorize_url: "http://localhost:4000/oauth/authorize",
      token_url: "/oauth/access_token",
      user_url: "/user",
      authorization_params: [scope: "email profile"],
      auth_method: :client_secret_post
    ]
  end

  @impl true
  def normalize(_config, user) do
    {:ok,
      # Conformed to https://openid.net/specs/openid-connect-core-1_0.html#rfc.section.5.1
      %{
        "sub"      => user["sub"],
        "name"     => user["name"],
        "nickname" => user["username"],
        "email"    => user["email"]
      # },
      # # Provider specific data not part of the standard claims spec
      # %{
      #   "http://localhost:4000/bio" => user["bio"]
      }
    }
  end
end

The normalized user map should conform to the OpenID Connect Core 1.0 Standard Claims spec, and should return either {:ok, userinfo_claims} or {:ok, userinfo_claims, additional}. Any keys defined in the userinfo claims that aren't part of the specs will not be included in the user map. Instead, they should be set in the additional data that will then be merged on top of the userinfo claims excluding any keys that have already been set.

You can use any of the Assent.Strategy.OAuth2.Base, Assent.Strategy.OAuth.Base, and Assent.Strategy.OIDC.Base macros to set up the strategy.

If you need more control over the strategy than what the macros give you, you can implement your provider using the Assent.Strategy behaviour:

defmodule TestProvider do
  @behaviour Assent.Strategy

  alias Assent.Strategy, as: Helpers

  @impl Assent.Strategy
  def authorize_url(config) do
    # Generate redirect URL

    {:ok, %{url: url}}
  end

  @impl Assent.Strategy
  def callback(config, params) do
    # Fetch user data

    user = Helpers.normalize_userinfo(userinfo)

    {:ok, %{user: user}}
  end
end

HTTP Client

Assent supports Req, Finch, and :httpc out of the box. The Req HTTP client adapter will be used by default if enabled, otherwise Erlang's :httpc adapter will be used.

You can explicitly set the HTTP client adapter in the configuration:

config = [
  client_id: "REPLACE_WITH_CLIENT_ID",
  client_secret: "REPLACE_WITH_CLIENT_SECRET",
  http_adapter: Assent.HTTPAdapter.Httpc
]

Or globally in the config:

config :assent, http_adapter: Assent.HTTPAdapter.Httpc

Req

Req doesn't require any additional configuration and will work out of the box:

defp deps do
  [
    # ...
    {:req, "~> 0.4"}
  ]
end

:httpc

If Req is not available, Erlangs built-in :httpc is used for requests. SSL verification is automatically enabled when :certifi and :ssl_verify_fun packages are available. :httpc only supports HTTP/1.1.

defp deps do
  [
    # ...
    # Required for SSL validation if using the `:httpc` adapter
    {:certifi, "~> 2.4"},
    {:ssl_verify_fun, "~> 1.1"}
  ]
end

You must include :inets to :extra_applications to include :httpc in your release.

Finch

Finch will require a supervisor in your application.

Update mix.exs:

defp deps do
  [
    # ...
    {:finch, "~> 0.16"}
  ]
end

Ensure you start the Finch supervisor in your application, and set :http_adapter in your provider configuration using your connection pool:

config = [
  client_id: "REPLACE_WITH_CLIENT_ID",
  client_secret: "REPLACE_WITH_CLIENT_SECRET",
  http_adapter: {Assent.HTTPAdapter.Finch, supervisor: MyFinch}
]

JWT Adapter

By default the built-in Assent.JWTAdapter.AssentJWT is used for JWT parsing, but you can change it to any third-party library with a custom Assent.JWTAdapter. A JOSE adapter Assent.JWTAdapter.JOSE is included.

To use JOSE, update mix.exs:

defp deps do
  [
    # ...
    {:jose, "~> 1.8"}
  ]
end

And pass the :jwt_adapter with your provider configuration:

config = [
  client_id: "REPLACE_WITH_CLIENT_ID",
  client_secret: "REPLACE_WITH_CLIENT_SECRET",
  jwt_adapter: Assent.JWTAdapter.JOSE
]

Or globally in the config:

config :assent, jwt_adapter: Assent.JWTAdapter.JOSE

Summary

Functions

Fetches the key value from the configuration.

Fetches the key value from the params.

Fetches the JSON library in config.

Functions

fetch_config(config, key)

@spec fetch_config(Keyword.t(), atom()) ::
  {:ok, any()} | {:error, Assent.MissingConfigError.t()}

Fetches the key value from the configuration.

Returns a Assent.MissingConfigError if the key is not found.

fetch_param(params, key)

@spec fetch_param(map(), binary()) ::
  {:ok, any()} | {:error, Assent.MissingParamError.t()}

Fetches the key value from the params.

Returns a Assent.MissingParamError if the key is not found.

json_library(config)

@spec json_library(Keyword.t()) :: module()

Fetches the JSON library in config.

If not found in provided config, this will attempt to load the JSON library from global application environment for :assent. Defaults to JSON.