Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Update docs around authentication to make them clearer where the route goes, and where the token is returned #255

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
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..."
}
}
```
Loading