# `Assent.Strategy.OAuth2`
[🔗](https://github.com/pow-auth/assent/blob/v0.4.0/lib/assent/strategies/oauth2.ex#L1)

OAuth 2.0 strategy.

This strategy only supports the Authorization Code flow per
[RFC 6749](https://tools.ietf.org/html/rfc6749#section-1.3.1).

`authorize_url/1` returns a map with a `:url` and `:session_params` key. The
`:session_params` should be stored and passed back into `callback/3` as part
of config when the user returns. The `:session_params` carries a `:state`
value for the request [to prevent
CSRF](https://tools.ietf.org/html/rfc6749#section-4.1.1). If `:code_verifier`
is set to true, the `:session_params` will also carry PKCE [code verification
parameters](https://datatracker.ietf.org/doc/html/rfc7636#section-4).

This library also supports JWT tokens for client authentication as per
[RFC 7523](https://tools.ietf.org/html/rfc7523).

## Configuration

  * `:client_id` - the OAuth2 client ID, required

  * `:base_url` - the base URL of the OAuth2 server, required

  * `:client_authentication_method` - the authentication strategy used,
    optional. If not set, no authentication will be used during the
    access token request (e.g. public clients). The value may be one of the
    following:

    * `:client_secret_basic` - authenticate with basic authorization header

    * `:client_secret_post` - authenticate with post params

    * `:client_secret_jwt` - authenticate with JWT using `:client_secret` as
      secret

    * `:private_key_jwt` - authenticate with JWT using `:private_key_path` or
      `:private_key` as secret

  * `:client_secret` - the OAuth2 client secret, required if
    `:client_authentication_method` is `:client_secret_basic`,
    `:client_secret_post`, or `:client_secret_jwt`

  * `:private_key_id` - the private key ID, required if
    `:client_authentication_method` is `:private_key_jwt`

  * `:private_key_path` - the path for the private key, required if
    `:client_authentication_method` is `:private_key_jwt` and `:private_key`
    hasn't been set

  * `:private_key` - the private key content that can be defined when
    `:client_authentication_method` is `:private_key_jwt` and
    `:private_key_path` hasn't been set

  * `:jwt_algorithm` - the algorithm to use for JWT signing, optional,
    defaults to `HS256` for `:client_secret_jwt` and `RS256` for
    `:private_key_jwt`

  * `:jwt_audience` - the audience for JWT client authentication, optional,
    defaults to the token endpoint URL

  * `:state` - a boolean or a string with the value of the state, optional,
    defaults to `true`. When set to `true` a random 32 byte long URL-safe
    string is generated. When set to `false` state will not be verified.

  * `:code_verifier` - boolean to generate and use a random 128 byte long
    URL-safe code verifier for PKCE flow, optional, defaults to `false`. When
    set to `true` the session params will contain `:code_verifier`,
    `:code_challenge`, and `:code_challenge_method` params.

## Usage

    defmodule OAuth2 do
      import Plug.Conn

      alias Assent.Strategy.OAuth2

      defp config do
        [
          client_id: Application.fetch_env!(:my_app, :oidc, :client_id),
          client_secret: Application.fetch_env!(:my_app, :oidc, :client_secret),
          client_authentication_method: :client_secret_post,
          base_url: "https://auth.example.com",
          authorization_params: [scope: "user:read user:write"],
          user_url: "https://example.com/api/user",
          redirect_uri: "http://localhost:4000/auth/callback"
        ]
      end

      def request(conn) do
        config()
        |> OAuth2.authorize_url()
        |> case do
          {:ok, %{url: url, session_params: session_params}} ->
            conn
            |> put_session(:session_params, session_params)
            |> put_resp_header("location", url)
            |> send_resp(302, "")

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

      def callback(conn) do
        %{params: params} = fetch_query_params(conn)
        session_params = get_session(conn, :session_params)
        conn = delete_session(conn, :session_params)

        config()
        |> Keyword.put(:session_params, session_params)
        |> OAuth2.callback(params)
        |> case do
          {:ok, %{user: user, token: token}} ->
            conn
            |> put_session(:user, user)
            |> put_session(:token, token)
            |> put_resp_header("location", "/")
            |> send_resp(302, "")

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

# `on_authorize_url`

```elixir
@type on_authorize_url() ::
  {:ok, %{session_params: session_params(), url: binary()}} | {:error, term()}
```

Return value of `authorize_url/1`.

# `on_callback`

```elixir
@type on_callback() :: {:ok, %{token: map(), user: map()}} | {:error, term()}
```

Return value of `callback/3`.

# `session_params`

```elixir
@type session_params() :: %{
  optional(:state) =&gt; binary(),
  optional(:code_verifier) =&gt; binary(),
  optional(:code_challenge) =&gt; binary(),
  optional(:code_challenge_method) =&gt; binary()
}
```

The session parameters returned from `authorize_url/1`, to be stored and
passed back into `callback/3`.

# `authorize_url`

```elixir
@spec authorize_url(Keyword.t()) :: on_authorize_url()
```

Generates an authorization URL for the request phase.

## Options

  * `:redirect_uri` - the URI that the server redirects the user to after
    authentication, required

  * `:authorize_url` - the path or URL for the OAuth2 server to redirect
    users to, defaults to `/oauth/authorize`

  * `:authorization_params` - the authorization parameters, defaults to `[]`

# `callback`

```elixir
@spec callback(Keyword.t(), map(), atom()) :: on_callback()
```

Callback phase for generating an access token with the authorization code
and fetching user data. Returns a map with access token in `:token` and user
data in `:user`.

## Options

  * `:token_url` - the path or URL to fetch the token from, optional,
    defaults to `/oauth/token`

  * `:user_url` - the path or URL to fetch user data, required

  * `:session_params` - the session parameters that were returned from
    `authorize_url/1`, optional

# `fetch_user`

```elixir
@spec fetch_user(Keyword.t(), map(), map() | Keyword.t(), [{binary(), binary()}]) ::
  {:ok, map()} | {:error, term()}
```

Fetches user data with the access token.

Uses `request/6` to fetch the user data.

# `grant_access_token`

```elixir
@spec grant_access_token(Keyword.t(), binary(), Keyword.t()) ::
  {:ok, map()} | {:error, term()}
```

Grants an access token.

# `refresh_access_token`

```elixir
@spec refresh_access_token(Keyword.t(), map(), Keyword.t()) ::
  {:ok, map()} | {:error, term()}
```

Refreshes the access token.

# `request`

```elixir
@spec request(Keyword.t(), map(), atom(), binary(), map() | Keyword.t(), [
  {binary(), binary()}
]) ::
  {:ok, map()} | {:error, term()}
```

Performs an HTTP request to the API using the access token.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
