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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
widianto
I think I’ve found a small improvement I could contribute to <%= web_namespace %>.CoreComponents (installer/templates/phx_web/compo...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews