Skip to content

Commit

Permalink
docs: Update docs around authentication to make them clearer where th…
Browse files Browse the repository at this point in the history
…e route goes, and where the token is returned
  • Loading branch information
sevenseacat committed Nov 10, 2024
1 parent a865498 commit 0a5e40e
Showing 1 changed file with 35 additions and 15 deletions.
50 changes: 35 additions & 15 deletions documentation/topics/authenticate-with-json-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,50 @@

Authenticating with AshJsonApi requires a few things. The first thing to note is that this is not something that is provided for you out of the box by `ash_authentication`.

You will need to
You will need to:

- connect the authentication action to a route manually
- need to extract the resulting authentication token
- set it as a header or as metadata to provide it to the client to use on future requests

You may also need to add a policy bypass to your resource, to make the action accessible via a non-AshAuthenticationPhoenix liveview.

## The route

In this example, we will use the standard `:sign_in_with_password` action that is created by `ash_authentication` under the hood, and we will return the token as top-level request metadata
In this example, we will use the standard `:sign_in_with_password` action that is created by `ash_authentication` under the hood, and we will return the token as part of the response metadata.

```elixir
# in your user resource
routes do
# read actions that return *only one resource* are allowed to be used with
# `post` routes.

post :sign_in_with_password do
route "/sign_in/:id"

# given a successful request, we will modify the route to include the
# generated token
metadata(fn _subject, user, _request ->
%{token: user.__metadata__.token}
end)
# In your User module
defmodule <YourApp>.<YourDomain>.User do
json_api do
routes do
# Read actions that return *only one resource* are allowed to be used with
# `post` routes.
post :sign_in_with_password do
route "/sign_in"

# Given a successful request, we will modify the response to include the
# generated token
metadata fn _subject, user, _request ->
%{token: user.__metadata__.token}
end
end
end
end
end
```

This will add the token to the `meta` key in a successful API response, eg.

```json
{
{
"data": {
"attributes": { ... },
...
},
"meta": {
"token": "eyJhbGc..."
}
}
```

0 comments on commit 0a5e40e

Please sign in to comment.