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

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New

Other Trending Topics Top

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
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
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews