adrian

adrian

Hello,

I have spent more than a day reading ash code, and this forum to understand how tokens work, but I still have some questions.

I figured out I can get the token like this:

user =
  Ash.Query.for_read(User, :sign_in_with_password, %{
    email: "email@example.com",
    password: "test"
  })
  |> Ash.read_one!()
token = Ash.Resource.get_metadata(user, :token)

But that token is not stored anywhere. I have read this in the generated resource code:

  # In the generated sign in components, we validate the
  # email and password directly in the LiveView
  # and generate a short-lived token that can be used to sign in over
  # a standard controller action, exchanging it for a standard token.
  # This action performs that exchange. If you do not use the generated
  # liveviews, you may remove this action, and set
  # `sign_in_tokens_enabled? false` in the password strategy.

What does it mean? An example of this in the docs would be nice :slight_smile:

I signed in using LiveView /sign-in but still I don’t see any token generated.

I feel this is a stupid question, but what is the workflow for getting the token and using it in the API?

Based on this reply, I understand I can create an API endpoint to sign in and get the password:

use Phoenix.Controller

def sign_in(conn, %{"username" => username, "password" => password}) do
  YourUserResource
  |> Ash.Query.for_read(:sign_in_with_password, %{username: username, password: password})
  |> YourApi.read_one()
  |> case do
    {:ok, user} ->
      conn |> put_status(200) |> json(%{token: user.__metadata__.token})
   {:error, error} ->
     # handle errors. You should get back an `Ash.Error.Forbidden` 
     # error with a nested error you can use to provide an error message
  end
end

But after trying that token in the :sign_in_with_token action, it doesn’t work.

    read :sign_in_with_token do
      # In the generated sign in components, we validate the
      # email and password directly in the LiveView
      # and generate a short-lived token that can be used to sign in over
      # a standard controller action, exchanging it for a standard token.
      # This action performs that exchange. If you do not use the generated
      # liveviews, you may remove this action, and set
      # `sign_in_tokens_enabled? false` in the password strategy.

      description "Attempt to sign in using a short-lived sign in token."
      get? true

      argument :token, :string do
        description "The short-lived sign in token."
        allow_nil? false
        sensitive? true
      end

      # validates the provided sign in token and generates a token
      prepare AshAuthentication.Strategy.Password.SignInWithTokenPreparation

      metadata :token, :string do
        description "A JWT that can be used to authenticate the user."
        allow_nil? false
      end
    end

I get the error:

password: Email or password was incorrect

I attach a screenshot of the error in ash admin.

I also tried in iex:

iex(17)> user = Ash.Query.for_read(User, :sign_in_with_token, %{token: token}) |> Ash.read_one!()

* (Ash.Error.Forbidden) 
Bread Crumbs:
  > Error returned from: Iapruebo.Accounts.User.sign_in_with_token

Forbidden Error

* Authentication failed
  (ash_authentication 4.3.5) lib/ash_authentication/errors/authentication_failed.ex:5: AshAuthentication.Errors.AuthenticationFailed."exception (overridable 2)"/1
  (ash_authentication 4.3.5) lib/ash_authentication/errors/authentication_failed.ex:22: AshAuthentication.Errors.AuthenticationFailed.exception/1
  (ash_authentication 4.3.5) lib/ash_authentication/strategies/password/sign_in_with_token_preparation.ex:52: anonymous fn/3 in AshAuthentication.Strategy.Password.SignInWithTokenPreparation.verify_token_and_constrain_query/2
  (ash 3.4.46) lib/ash/actions/read/read.ex:2364: anonymous fn/2 in Ash.Actions.Read.run_before_action/1
  (elixir 1.17.3) lib/enum.ex:4858: Enumerable.List.reduce/3
  (elixir 1.17.3) lib/enum.ex:2585: Enum.reduce_while/3
  (ash 3.4.46) lib/ash/actions/read/read.ex:2363: Ash.Actions.Read.run_before_action/1
  (ash 3.4.46) lib/ash/actions/read/read.ex:582: anonymous fn/8 in Ash.Actions.Read.do_read/5
  (ash 3.4.46) lib/ash/actions/read/read.ex:938: Ash.Actions.Read.maybe_in_transaction/3
  (ash 3.4.46) lib/ash/actions/read/read.ex:319: Ash.Actions.Read.do_run/3
  (ash 3.4.46) lib/ash/actions/read/read.ex:82: anonymous fn/3 in Ash.Actions.Read.run/3
  (ash 3.4.46) lib/ash/actions/read/read.ex:81: Ash.Actions.Read.run/3
  (ash 3.4.46) lib/ash.ex:2105: Ash.do_read_one/3
  (ash 3.4.46) lib/ash.ex:2053: Ash.read_one/2
  (ash 3.4.46) lib/ash.ex:2018: Ash.read_one!/2
  (elixir 1.17.3) src/elixir.erl:386: :elixir.eval_external_handler/3
  (stdlib 6.2) erl_eval.erl:919: :erl_eval.do_apply/7
  (stdlib 6.2) erl_eval.erl:663: :erl_eval.expr/6
  (elixir 1.17.3) src/elixir.erl:364: :elixir.eval_forms/4
    (ash 3.4.46) lib/ash/error/forbidden.ex:3: Ash.Error.Forbidden.exception/1
    (ash 3.4.46) /home/antares/proyectos/iapruebo/deps/splode/lib/splode.ex:264: Ash.Error.to_class/2
    (ash 3.4.46) lib/ash/error/error.ex:108: Ash.Error.to_error_class/2
    (ash 3.4.46) lib/ash/actions/read/read.ex:390: anonymous fn/3 in Ash.Actions.Read.do_run/3
    (ash 3.4.46) lib/ash/actions/read/read.ex:335: Ash.Actions.Read.do_run/3
    (ash 3.4.46) lib/ash/actions/read/read.ex:82: anonymous fn/3 in Ash.Actions.Read.run/3
    (ash 3.4.46) lib/ash/actions/read/read.ex:81: Ash.Actions.Read.run/3
    (ash 3.4.46) lib/ash.ex:2105: Ash.do_read_one/3
    (ash 3.4.46) lib/ash.ex:2053: Ash.read_one/2
    (ash 3.4.46) lib/ash.ex:2018: Ash.read_one!/2
    iex:17: (file)

I am sure I’m misunderstanding some principle, but I can’t figure out what.

A workflow example in the docs would be nice. Once I understand it, I can add it to the docs.

Thanks a lot!

Showing Posts 1 to 6

sevenseacat

sevenseacat

Author of Ash Framework

Authentication tokens by default aren’t stored on the backend - they’re JWTs, that get validated on every request. If you want to store them all using the Token resource, you can enable that with store_all_tokens?

The sign_in_with_token action is only for use with AshAuthenticationPhoenix’s liveviews - if you are building an API with authentication, you can use the token directly in headers when making API requests, eg. Authentication: Bearer <token>.

adrian

adrian OP

Thanks @sevenseacat!

And how does sign_in_with_token work in live views? I’m interested in learning about that, too.

Shouldn’t that action login the user with the token received from :sign_in_with_token? Otherwise, I don’t understand what the action does.

Where can I learn more about token expirations, renewals, and revocations?

I guess the options we have are:

  • storing the tokens and check if they are revoked
  • create short-lived tokens, and refresh them frequently

Does the docs or the code cover any of these subjects?

AFAIK Ash hasn’t implemented token refresh yet, so the only option is to store the tokens and revoke them when needed, right?

Thanks!

zachdaniel

zachdaniel

Creator of Ash

That action takes a short lived token with the purpose of “sign_in” and exchanges it for a long lived token that is good for the standard duration.

This exists due to the implementation of liveview. The log in views are liveviews and a liveview cannot put anything into the session except on page load (at least not when we built it, although maybe something could be done with hooks, not sure) and we wanted to support immediate feedback when you submit the form. So the liveview calls the sign in with password action which validates your credentials on the spot. If they are wrong you get a standard form error, if they are right you get redirected to an endpoint with your short lived sign in token to exchange for a long lived token that gets put in the session. Because the LV couldn’t modify the session, and we don’t want to send the username and password in a redirect (we cannot it would be insecure) a sign in token was the only way to be secure while having the UX we wanted.

To get a short lived sign in token that can be used with that endpoint, you’d need to set this context:

https://github.com/team-alembic/ash_authentication_phoenix/blob/718b79213c56a63dadf0d2154d3a1d0d2863c092/lib/ash_authentication_phoenix/components/password/sign_in_form.ex#L160

In terms of “where can you read about” the docs are on hexdocs. If what you’re looking for isn’t there then it isn’t anywhere. However, it can be easy to miss the DSL docs. Scroll down and look in the bottom of the sidebar, which has docs for every option.

What specifically are you trying to do/implement? It’s possible there is some X/Y problem going on here. You’re asking about sign in tokens but they are for a single purpose which is signing in over a liveview.

Folks have implemented their own token refresh system on top of ash authentication’s token it just isn’t built in yet, so that is very much an option :slight_smile:

Perhaps ask in the discord to see if someone can share their implementation? If they do, ask them to share it here so others can find it.

adrian

adrian OP

Thank you again for your detailed reply, @zachdaniel! I’m sorry for my late reply; I was on holiday.

I am starting a project with Ash and Phoenix. When I start a project, I usually create data in the seeds.exs file. The file is idempotent, and it should provide the same data to all developers when they set up the project.

The first thing I do, is create the users. I realized I could create the user, but it wasn’t validated. I know I can just set the confirmed_at value, but I want to follow the expected workflow when working with Ash and users.

This is what I have in the script:

IO.puts("1. Create the user")
email = "adrian@mydomain.com"

user =
  case Iapruebo.Accounts.User.get_by_email(email, authorize?: false) do
    {:ok, user} ->
      user

    {:error, _} ->
      user =
        Iapruebo.Accounts.User
        |> Ash.Changeset.for_create(:register_with_password, %{
          email: email,
          password: "1234",
          password_confirmation: "1234"  # Do you think I use this password in all my accounts? :-)
        })
        |> Ash.create!(authorize?: false)

      confirmation_token = Ash.Resource.get_metadata(user, :confirmation_token)

      user
      |> Ash.Changeset.for_update(:confirm, %{
        confirm: confirmation_token
      })
      |> Ash.update!()
  end

IO.puts("User created: #{user.email}")

I investigated how Ash expected me to create and validate a user programmatically, but If couldn’t figure it out.

I was thinking about the short-lived token as the Phoenix authentication token.

I got lost in several things I didn’t understand, like auto_confirm_actions and monitor_fields.

So, I wanted to create the user and validate it in the seed script.

Thanks!

zachdaniel

zachdaniel

Creator of Ash

You can also look into Ash.Seed to inset data directly into the database if you like. It supports upserts.

adrian

adrian OP

Didn’t know about it, thanks!

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews