AshAuthentication.Strategy.OAuth2 (ash_authentication v5.0.0-rc.14)

Copy Markdown View Source

Strategy for authenticating using any OAuth 2.0 server as the source of truth.

This authentication strategy provides registration and sign-in for users using a remote OAuth 2.0 server as the source of truth. You will be required to provide either a "register" or a "sign-in" action depending on your configuration, which the strategy will attempt to validate for common misconfigurations.

This strategy wraps the excellent assent package, which provides OAuth 2.0 capabilities.

In order to use OAuth 2.0 authentication on your resource, it needs to meet the following minimum criteria:

  1. Have a primary key.
  2. Provide a strategy-specific action, either register or sign-in.
  3. Provide configuration for OAuth2 destinations, secrets, etc.

Example:

defmodule MyApp.Accounts.User do
  use Ash.Resource,
    extensions: [AshAuthentication],
    domain: MyApp.Accounts

  attributes do
    uuid_primary_key :id
    attribute :email, :ci_string, allow_nil?: false
  end

  authentication do
    strategies do
      oauth2 :example do
        client_id "OAuth Client ID"
        redirect_uri "https://my.app/"
        client_secret "My Super Secret Secret"
        site "https://auth.example.com/"
      end
    end
  end
end

Secrets and runtime configuration

In order to use OAuth 2.0 you need to provide a varying number of secrets and other configuration which may change based on runtime environment. The AshAuthentication.Secret behaviour is provided to accommodate this. This allows you to provide configuration either directly on the resource (ie as a string), as an anonymous function, or as a module.

Warning

We strongly urge you not to share actual secrets in your code or repository.

Examples:

Providing configuration as an anonymous function:

oauth2 do
  client_secret fn _path, resource ->
    Application.fetch_env(:my_app, resource, :oauth2_client_secret)
  end
end

Providing configuration as a module:

defmodule MyApp.Secrets do
  use AshAuthentication.Secret

  def secret_for([:authentication, :strategies, :example, :client_secret], MyApp.User, _opts), do: Application.fetch_env(:my_app, :oauth2_client_secret)
end

# and in your strategies:

oauth2 :example do
  client_secret MyApp.Secrets
end

User identities

Because your users can be signed in via multiple providers at once, you can specify an identity_resource in the DSL configuration which points to a seperate Ash resource which has the AshAuthentication.UserIdentity extension present. This resource will be used to store details of the providers in use by each user and a relationship will be added to the user resource.

Setting the identity_resource will cause extra validations to be applied to your resource so that changes are tracked correctly on sign-in or registration.

Actions

When using an OAuth 2.0 provider you need to declare either a "register" or "sign-in" action. The reason for this is that it's not possible for us to know ahead of time how you want to manage the link between your user resources and the "user info" provided by the OAuth server.

Both actions receive the following two arguments:

  1. user_info - a map with string keys containing the OpenID Successful UserInfo response. Usually this will be used to populate your email, nickname or other identifying field.
  2. oauth_tokens a map with string keys containing the OpenID Successful Token response (or similar).

The actions themselves can be interacted with directly via the AshAuthentication.Strategy protocol, but you are more likely to interact with them via the web/plugs.

Sign-in

The sign-in action is called when a successful OAuth2 callback is received. You should use it to constrain the query to the correct user based on the arguments provided.

This action is only needed when the registration_enabled? DSL settings is set to false.

Registration

The register action is a little more complicated than the sign-in action, because we cannot tell the difference between a new user and a returning user (they all use the same OAuth flow). In order to handle this your register action must be defined as an upsert with a configured upsert_identity (see example below).

Examples:

Providing sign-in to users who already exist in the database (and by extension rejecting new users):

defmodule MyApp.Accounts.User do
  attributes do
    uuid_primary_key :id
    attribute :email, :ci_string, allow_nil?: false
  end

  actions do
    read :sign_in_with_example do
      argument :user_info, :map, allow_nil?: false
      argument :oauth_tokens, :map, allow_nil?: false, sensitive?: true
      prepare AshAuthentication.Strategy.OAuth2.SignInPreparation

      filter expr(email == get_path(^arg(:user_info), [:email]))
    end
  end

  authentication do
    strategies do
      oauth2 :example do
        registration_enabled? false
      end
    end
  end
end

Providing registration or sign-in to all comers:

defmodule MyApp.Accounts.User do
  attributes do
    uuid_primary_key :id
    attribute :email, :ci_string, allow_nil?: false
  end

  actions do
    create :register_with_oauth2 do
      argument :user_info, :map, allow_nil?: false
      argument :oauth_tokens, :map, allow_nil?: false, sensitive?: true
      upsert? true
      upsert_identity :email

      change AshAuthentication.GenerateTokenChange
      change fn changeset, _ctx ->
        user_info = Ash.Changeset.get_argument(changeset, :user_info)

        changeset
        |> Ash.Changeset.change_attribute(:email, user_info["email"])
      end
    end
  end

  authentication do
    strategies do
      oauth2 :example do
      end
    end
  end
end

Plugs

OAuth 2.0 is (usually) a browser-based flow. This means that you're most likely to interact with this strategy via it's plugs. There are two phases to authentication with OAuth 2.0:

  1. The request phase, where the user's browser is redirected to the remote authentication provider for authentication.
  2. The callback phase, where the provider redirects the user back to your app to create a local database record, session, etc.

Summary

Functions

The changeset or query context an OAuth2-derived action runs with.

The connection id carried into the action by action_context/1.

The value stored in (and matched against) the user identity resource's strategy field for the given runtime strategy.

Restore a runtime connection id onto a strategy rebuilt from the compile-time DSL.

Extract the unique provider identifier (the OpenID Connect sub claim) from a provider's user_info map.

Types

secret()

@type secret() :: nil | String.t() | {module(), keyword()}

secret_keyword()

@type secret_keyword() :: nil | Keyword.t() | {module(), keyword()}

secret_list()

@type secret_list() :: nil | [any()] | {module(), keyword()}

t()

@type t() :: %AshAuthentication.Strategy.OAuth2{
  __spark_metadata__: Spark.Dsl.Entity.spark_meta(),
  assent_strategy: module(),
  auth_method:
    nil
    | :client_secret_basic
    | :client_secret_post
    | :client_secret_jwt
    | :private_key_jwt,
  authorization_params: secret_keyword(),
  authorize_url: secret(),
  base_url: secret(),
  client_authentication_method: nil | binary(),
  client_id: secret(),
  client_secret: secret(),
  code_verifier: secret(),
  email_field: atom(),
  icon: nil | atom(),
  id_token_signed_response_alg: nil | binary(),
  id_token_ttl_seconds: nil | pos_integer(),
  identity_relationship_name: atom(),
  identity_relationship_user_id_attribute: atom(),
  identity_resource: module() | false,
  idp_initiated_login?: boolean(),
  name: atom(),
  nonce: boolean() | secret(),
  on_untrusted_email_match: :reject | :confirm,
  openid_configuration: nil | map(),
  openid_configuration_uri: nil | binary(),
  prevent_hijacking?: boolean(),
  private_key: secret(),
  private_key_id: secret(),
  private_key_path: secret(),
  provider: atom(),
  redirect_uri: secret(),
  register_action_name: atom(),
  registration_enabled?: boolean(),
  resource: module(),
  sign_in_action_name: atom(),
  site: secret(),
  strategy_module: module(),
  team_id: secret(),
  token_url: secret(),
  trust_email_verified?: boolean(),
  trusted_audiences: secret_list(),
  user_url: secret(),
  warn_on_missing_identity_resource?: boolean()
}

Functions

action_context(strategy)

@spec action_context(t() | map()) :: map()

The changeset or query context an OAuth2-derived action runs with.

Carries the connection id of the runtime strategy, if it has one, so that changes and preparations can restore it onto the strategy they rebuild from the compile-time DSL. It lives under private, which Ash never populates from action params: the id must come from the connection lookup AshAuthentication.Strategy.DynamicOidc.Plug performs, never from the request. Were it caller-supplied, the identity namespace would be caller-chosen.

connection_id_from_context(context)

@spec connection_id_from_context(map()) :: nil | String.t()

The connection id carried into the action by action_context/1.

Takes a changeset's or query's context.

identity_strategy_name(strategy)

@spec identity_strategy_name(t() | map()) :: String.t()

The value stored in (and matched against) the user identity resource's strategy field for the given runtime strategy.

For most strategies this is the bare strategy name. For dynamic_oidc - whose connection configuration is data-driven per tenant/customer - it is namespaced with the matched connection id ("<name>/<connection_id>") so that IdPs which may issue colliding sub claims are disambiguated. This is the single source of truth for every read of and write to that field: IdentityChange, SignInPreparation, UserResolver and the confirmation add-on's identity link all go through it.

A namespaced strategy has to carry its connection id by the time this is called. See put_connection_id/2.

put_connection_id(strategy, connection_id)

@spec put_connection_id(t() | map(), nil | String.t()) :: {:ok, t() | map()} | :error

Restore a runtime connection id onto a strategy rebuilt from the compile-time DSL.

A strategy whose identity namespace is per-connection carries a __connection_id__ field, which only the plug populates. AshAuthentication.Info.strategy_for_action/2 and find_strategy/3 return the DSL struct, whose field is nil, so the id has to be put back before identity_strategy_name/1 is used.

Returns :error when the strategy needs a connection id and none is available. Callers must fail the action: falling back to the bare strategy name collapses every connection into one identity namespace, which is what the namespace exists to prevent. A strategy without the field needs no id and comes back unchanged.

transform(entity, dsl_state)

Callback implementation for AshAuthentication.Strategy.Custom.transform/2.

uid_from_user_info(user_info)

@spec uid_from_user_info(map()) :: String.t() | nil

Extract the unique provider identifier (the OpenID Connect sub claim) from a provider's user_info map.

The first key present with a non-nil value wins, in this order: sub is the OpenID Connect claim and the key the whole identity model is built on, uid is the AshAuthentication convention for the same thing, and id is a fallback for providers (eg Google in the past) which returned id instead of sub. The same extraction must be used both when looking a user up by their identity and when persisting the identity, so this is the single source of truth.

verify(strategy, dsl_state)

Callback implementation for AshAuthentication.Strategy.Custom.verify/2.