Multi-provider authentication framework.
Features
- Includes the following base strategies:
- OAuth 1.0a -
Assent.Strategy.OAuth - OAuth 2.0 -
Assent.Strategy.OAuth2 - OpenID Connect -
Assent.Strategy.OIDC
- OAuth 1.0a -
- Includes the following provider strategies:
- Apple Sign In -
Assent.Strategy.Apple - Auth0 -
Assent.Strategy.Auth0 - Azure AD -
Assent.Strategy.AzureAD - Basecamp -
Assent.Strategy.Basecamp - Bitbucket -
Assent.Strategy.Bitbucket - DigitalOcean -
Assent.Strategy.DigitalOcean - Discord -
Assent.Strategy.Discord - Facebook -
Assent.Strategy.Facebook - GitHub -
Assent.Strategy.Github - GitLab -
Assent.Strategy.Gitlab - Google -
Assent.Strategy.Google - LINE Login -
Assent.Strategy.LINE - LinkedIn -
Assent.Strategy.Linkedin - Slack -
Assent.Strategy.Slack - Spotify -
Assent.Strategy.Spotify - Strava -
Assent.Strategy.Strava - Stripe Connect -
Assent.Strategy.Stripe - Telegram -
Assent.Strategy.Telegram - Twitch -
Assent.Strategy.Twitch - Twitter -
Assent.Strategy.Twitter - VK -
Assent.Strategy.VK - Zitadel -
Assent.Strategy.Zitadel
- Apple Sign In -
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 are 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 successful
conn
|> put_session(:user, user)
|> put_session(:token, token)
|> put_resp_header("location", "/")
|> send_resp(302, "")
{:error, _error} ->
# Authorization failed
send_resp(conn, 500, "Failed authorization")
end
end
endMulti-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 strategiesdefmodule MultiProviderAuth do
@spec authorize_url(atom()) :: {:ok, map()} | {:error, term()}
def authorize_url(provider) do
config = config!(provider)
config[:strategy].authorize_url(config)
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
endCustom 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",
# Defining 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"],
client_authentication_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
endThe 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
case Helpers.normalize_userinfo(userinfo) do
{:ok, user} -> {:ok, %{user: user}}
{:error, reason} -> {:error, reason}
end
end
endHTTP request rewrites
Strategies can rewrite HTTP requests before they are sent. This example adds a custom header to requests for a particular endpoint:
defmodule TestProvider do
# ...
def default_config(_config) do
[
base_url: "https://example.com",
token_url: "https://api.example.com/oauth/token",
prepare_http_request: {__MODULE__, :prepare_http_request, []}
]
end
def prepare_http_request(request) do
case URI.parse(request.url) do
%{host: "api.example.com"} -> %{request | headers: [{"x-api-version", "1"} | request.headers]}
_other -> request
end
end
# ...
endHTTP Client
Assent supports Req 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.HttpcReq
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, Erlang's built-in :httpc is used for requests. SSL verification is enabled automatically. :httpc only supports HTTP/1.1.
You can override the :ssl options to use your own trust store or verify function:
config = [
client_id: "REPLACE_WITH_CLIENT_ID",
client_secret: "REPLACE_WITH_CLIENT_SECRET",
http_adapter: {Assent.HTTPAdapter.Httpc, ssl: [cacertfile: ~c"/path/to/ca.pem"]}
]HTTPS requests configured with ssl: [verify: :verify_none, ...] are rejected. Pass a custom :verify_fun to handle verification yourself. See Assent.HTTPAdapter.Httpc for more.
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"}
]
endAnd 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 key value from the token.
Fetches the JSON library in config.
Functions
@spec fetch_config(Keyword.t(), atom()) :: {:ok, any()} | {:error, Assent.MissingConfigError.t()}
Fetches the key value from the configuration.
Returns an Assent.MissingConfigError if the key is not found.
@spec fetch_param(map(), binary()) :: {:ok, any()} | {:error, Assent.MissingParamError.t()}
Fetches the key value from the params.
Returns an Assent.MissingParamError if the key is not found.
@spec fetch_token_param(map(), binary()) :: {:ok, any()} | {:error, Assent.MissingParamError.t()}
Fetches the key value from the token.
Returns an Assent.MissingParamError if the key is not found.
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.