Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/ash_authentication/dsl.ex
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ defmodule AshAuthentication.Dsl do
"The resource used to store token information, such as in-flight confirmations, revocations, and if `store_all_tokens?` is enabled, authentication tokens themselves.",
required: true
],
extra_claims: [
type: {:or, [{:fun, 2}, :map]},
doc:
"A function that takes the user and the options provided when generating a token (contains the tenant), and returns a map of extra claims to include in the token."
],
signing_secret: [
type: secret_type,
doc: "The secret used to sign tokens. #{secret_doc}"
Expand Down
24 changes: 23 additions & 1 deletion lib/ash_authentication/jwt.ex
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,13 @@
default_claims = Config.default_claims(resource, action_opts)
signer = Config.token_signer(resource, opts, context)

with {:ok, token, claims} <- Joken.generate_and_sign(default_claims, extra_claims, signer),
with {:ok, more_extra_claims} <- extra_claims_for_user(purpose, user, opts),
{:ok, token, claims} <-
Joken.generate_and_sign(
default_claims,
Map.merge(extra_claims, more_extra_claims),
signer
),
:ok <- maybe_store_token(token, resource, user, purpose, action_opts) do
{:ok, token, claims}
else
Expand All @@ -120,6 +126,22 @@
end
end

defp extra_claims_for_user(:user, user, opts) do
case AshAuthentication.Info.authentication_tokens_extra_claims(user) do
:error ->
%{}

{:ok, nil} ->

Check warning on line 134 in lib/ash_authentication/jwt.ex

View workflow job for this annotation

GitHub Actions / mix dialyzer

pattern_match

The pattern can never match the type {:ok, (_, _ -> any()) | map()}.
%{}

{:ok, extra_claims} when is_map(extra_claims) ->
extra_claims

{:ok, extra_claims} when is_function(extra_claims) ->
extra_claims.(user, opts)
end
end

@doc """
Given a resource, generate a signed JWT with a set of claims.
"""
Expand Down
2 changes: 2 additions & 0 deletions lib/ash_authentication/plug/helpers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ defmodule AshAuthentication.Plug.Helpers do
),
{:ok, subject_name} <- Info.authentication_subject_name(resource),
current_subject_name <- current_subject_name(subject_name) do
user = Ash.Resource.set_metadata(user, %{claims: claims})

conn
|> Conn.assign(current_subject_name, user)
|> maybe_assign_token_record(token_record, subject_name)
Expand Down
Loading