Get started with Ash Authentication

View Source

If you haven't already, read the getting started guide for Ash. This assumes that you already have resources set up, and only gives you the steps to add authentication to your resources and APIs.

Install the extension

mix igniter.install ash_authentication --auth-strategy magic_link,password
Using Phoenix?

Use the following. If you have not yet run the above command, this will prompt you to do so, so you can run both or only this one.

mix igniter.install ash_authentication_phoenix --auth-strategy magic_link,password

Choose your strategies and add-ons

mix ash_authentication.add_strategy

A mix task is provided to add strategies and add-ons to your application. For now, this only supports the password strategy, but more will be added in the future.

mix ash_authentication.add_strategy password

Strategies

Add-Ons

Set up your Phoenix or Plug application

If you're using Phoenix, skip this section and go to Integrating Ash Authentication and Phoenix

In order for your users to be able to sign in, you will likely need to provide an HTTP endpoint to submit credentials or OAuth requests to. Ash Authentication provides AshAuthentication.Plug for this purposes. It provides a use macro which handles routing of requests to the correct providers, and defines callbacks for successful and unsuccessful outcomes.

Let's generate our plug:

# lib/my_app/auth_plug.ex

defmodule MyApp.AuthPlug do
  use AshAuthentication.Plug, otp_app: :my_app

  def handle_success(conn, _activity, user, token) do
    if is_api_request?(conn) do
      conn
      |> send_resp(200, Jason.encode!(%{
        authentication: %{
          success: true,
          token: token
        }
      }))
    else
      conn
      |> store_in_session(user)
      |> send_resp(200, EEx.eval_string("""
      <h2>Welcome back <%= @user.email %></h2>
      """, user: user))
    end
  end

  def handle_failure(conn, _activity, _reason) do
    if is_api_request?(conn) do
      conn
      |> send_resp(401, Jason.encode!(%{
        authentication: %{
          success: false
        }
      }))
    else
      conn
      |> send_resp(401, "<h2>Incorrect email or password</h2>")
    end
  end

  defp is_api_request?(conn), do: "application/json" in get_req_header(conn, "accept")
end

Now that this is done, you can forward HTTP requests to it from your app's main router using forward "/auth", to: MyApp.AuthPlug or similar.

Your generated auth plug module will also contain load_from_session and load_from_bearer function plugs, which can be used to load users into assigns based on the contents of the session store or Authorization header.

Summary

In this guide we've learned how to install Ash Authentication, configure resources and handle authentication HTTP requests.

You should now have an Ash application with working user authentication.

Up next, Using with Phoenix