Testing with AshAuthentication after upgrade

After upgrading ash_authentication_phoenix and ash_authentication to 2.10.0 and 2.9.2, this test helper function raises an error.
@doc """
Logs in a user with `AshAuthentication` as the current user.
"""
def log_in_user_as_subject(conn, user) do
conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Phoenix.Plug.store_in_session(user)
|> Plug.Conn.assign(:current_user, user)
end
@doc """
Logs in a user with `AshAuthentication` as the current user.
"""
def log_in_user_as_subject(conn, user) do
conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Phoenix.Plug.store_in_session(user)
|> Plug.Conn.assign(:current_user, user)
end
** (KeyError) key :token not found in: %{}
code: conn = log_in_user_as_subject(conn, user)
stacktrace:
(ash_authentication 4.9.2) lib/ash_authentication/plug/helpers.ex:18: AshAuthentication.Plug.Helpers.store_in_session/2
** (KeyError) key :token not found in: %{}
code: conn = log_in_user_as_subject(conn, user)
stacktrace:
(ash_authentication 4.9.2) lib/ash_authentication/plug/helpers.ex:18: AshAuthentication.Plug.Helpers.store_in_session/2
Looks like it's because I'm creating users for test using Ash.Seed.seed!, so nothing is populating token.
User
|> Ash.Seed.seed!(%{email: "bob@example.net", hashed_password: "..."})
User
|> Ash.Seed.seed!(%{email: "bob@example.net", hashed_password: "..."})
What would be a sensible fix here?
Solution:
🤔 You could generate a token and put it into __metadata__
Jump to solution
3 Replies
Solution
ZachDaniel
ZachDaniel•4mo ago
🤔 You could generate a token and put it into __metadata__
ZachDaniel
ZachDaniel•4mo ago
With AshAuthentication.Jwt.token_for_user
allenwyma
allenwyma•4mo ago
this works well:
@doc """
Logs in a user to a conn for testing.
"""
@spec login_user(Plug.Conn.t(), App.Accounts.User.t()) :: Plug.Conn.t()
def login_user(conn, user) do
user =
case Ash.Resource.get_metadata(user, :token) do
nil ->
{:ok, token, _claims} = AshAuthentication.Jwt.token_for_user(user)
Ash.Resource.set_metadata(user, %{token: token})

_token ->
user
end

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(user)
end
@doc """
Logs in a user to a conn for testing.
"""
@spec login_user(Plug.Conn.t(), App.Accounts.User.t()) :: Plug.Conn.t()
def login_user(conn, user) do
user =
case Ash.Resource.get_metadata(user, :token) do
nil ->
{:ok, token, _claims} = AshAuthentication.Jwt.token_for_user(user)
Ash.Resource.set_metadata(user, %{token: token})

_token ->
user
end

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(user)
end

Did you find this page helpful?