lud

lud

Hello,

I’m trying out the Ash framework for the first time. I am building an API for a mobile app and I want to implement user authentication.

We are in a first-party app and server configuration, so after reading this I’m wondering if the following could be enough:

  • An API endpoint accepting email/password and sending a token
  • An API endpoint using Ash Token features

It’s the first time I’m doing a mobile app so I am not sure. But to me it looks like I do not need to implement OAuth2 or OID Connect.

What do you think?

Thanks!

Showing Posts 1 to 10

D4no0

D4no0

Usually if there is mobile involved, there is the google/ios authentication involved. They basically send you a JWT token instead of username/password that you can check for validity against their public certificates.

zachdaniel

zachdaniel

Creator of Ash

If you can leverage oauth2 that would be ideal as ash_authentication has native support for that. :grinning_face:

zachdaniel

zachdaniel

Creator of Ash

Not that you need to, though. You can pretty easily create an endpoint that calls the sign_in_with_password action and extracts the token.

lud

lud OP

I’m trying to understand if I need OAuth2 in my context. What would be the benefits when I am in control of both the app and server?

zachdaniel

zachdaniel

Creator of Ash

well, if you wanted to support social sign on, for example. If you want to provide username/password login, you definitely don’t need oauth2 for that. The suggestion isn’t for your application to be an oauth2 provider, that is definitely overkill (and its not something ash_authentication does for you).

lud

lud OP

Yes thanks for the distinction. I see too many apps implementing both OAuth2 provider and clients for authentication and it never makes sense.

For social sign on the token I would get would be provided by, say, facebook. That token would allow me to fetch user data from facebook, or get an OpenID payload. But it is not a token I would use from the mobile app to connect to my API and fetch user data from my server app API. So I still need a custom token delivered by my server app, OAuth2 as a client does not help here. Am I correct ?

zachdaniel

zachdaniel

Creator of Ash

Correct. You’d want to implement the password strategy. That strategy will add all the actions that you need to your resources. I don’t think that a JSON endpoint is created for you for signing in, but if not it is something you should be able to do with a phoenix controller.

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
lud

lud OP

Yes thank you, that is what I intended to do :slight_smile: So ok for now I’ll just have that special endpoint and an API with token, no OAuth2 needed.

zachdaniel

zachdaniel

Creator of Ash

Yep! That sounds right to me :slight_smile:

lud

lud OP

Hi again! I decided to tackle this tonight.

I am not sure I understand correctly. What exactly is user.__metadata__.token?

For now I’m just trying this from a test:

    email = "test@test.com"
    password = "supersecret"

    payload = %{
      "user" => %{
        "email" => email,
        "password" => password,
        "password_confirmation" => password
      }
    }

    conn = post(conn, ~p"/auth/user/password/register", payload)
    data = json_response(conn, 200))

But I do not understand why the token is present in the user in the metadata. I created a MyApp.Accounts.Token entity like the tutorial said, but now I understand that those are for server-side-only metadata about the tokens. Do they target that same token I found in my user struct metadata?

It seems so.

So now I would like the user to sign-up and then be able to sign-in from different machines and revoke their login from a specific machine.

In the AuthController I did this in the success callback:

    Token
    |> Ash.Changeset.for_create(:store_token,
      token: user.__metadata__.token,
      purpose: "hello world"
    )
    |> Accounts.create!()
    |> dbg()

I seems that the purpose is not relevant for Ash to work, though required. So I can add the machine based on the user agent or a custom header or field. And I can now write a basic test controller like this :smiley:

  def check(conn, params) do
    resp_payload =
      case conn.assigns do
        %{current_user: user} -> %{logged_in: true, as: user.email}
        _ -> %{logged_in: false}
      end

    conn
    |> put_status(200)
    |> json(resp_payload)
  end

And run my full test to see if it worked:

  test "a user can authenticate via API using email and password", %{conn: base_conn} do
    # Create a user from API

    email = "test@test.com"
    password = "supersecret"

    payload = %{
      "user" => %{
        "email" => email,
        "password" => password,
        "password_confirmation" => password
      }
    }

    conn = post(base_conn, ~p"/auth/user/password/register", payload)
    _data_signup = json_response(conn, 200)

    # Now sign in
    conn = post(base_conn, ~p"/auth/user/password/sign_in", payload)
    data_signin = json_response(conn, 200)

    # Try the API without the token
    conn = get(base_conn, ~p"/api/check")
    data_checkwo = json_response(conn, 200)
    assert false == data_checkwo["logged_in"]

    # Try with
    conn =
      base_conn
      |> Plug.Conn.put_req_header(
        "authorization",
        "Bearer #{Map.fetch!(data_signin, "bearer_token")}"
      )
      |> get(~p"/api/check")

    data_checkwith = json_response(conn, 200)
    assert true == data_checkwith["logged_in"]
    assert email == data_checkwith["as"]
  end

Now I realize that there is not really a question in my message :smiley: I’ll try to create another resource and have readable by the owner only.

I added this in my router:

  import AshAuthentication.Plug.Helpers

And the new plug here:


  pipeline :api do
    plug :accepts, ["json"]

    # Ash
    plug :load_from_bearer
    plug :set_actor, :user
  end

But in the controller Ash.get_actor is always nil. I have seen that the plug only sets it in conn.private.ash.actor. So I guess I should write a custom plug to forbid some api routes to be accessed without authentication. Is that how you would do it? I do not need any public data on those routes.

Or would you rather just always set an actor on the action, even if it is nil, and let the policies reject the calls?

Thank you for reading, sorry for that unstructured post :smiley: it took me a couple hours to write because I implemented the code along.

Where Next? Top

Trending in Questions Top

itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New
rlipscombe
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used? I’ve got two Github accoun...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews