jarvism

jarvism

Get Token for Protected API Routes via API (not UI)

Hello!
I have a Phoenix 1.7 LiveView app up and running with auth via
mix phx.gen.auth Accounts User users.
I’m still learning, but really enjoying it so far!
I’m running into a situation, though, where I am not quite sure even how to ask. Basically, I want to allow API users (outside of the LiveView) to access protected routes.
If I try to POST to /users/log_in, I get CSRF errors, which I think is correct. So, what is the correct way to get a token to use with the API?
Should I

  1. use mix phx.gen.secret to
  2. add an API key table with the user ID as a foreign key
  3. build my own plug to check the API key
  4. use Phoenix.Token to return a token if the API key is in the table?

I feel like I’m probably missing something since this must be a common use case with a canonical implementation.
Please point me in the right direction.
Thank you!

Most Liked

mindok

mindok

I’m not that qualified in this area, and our authentication system was built on the back of Ash Authentication rather than using phx.gen.auth. However, the following may give you some pointers:

  1. In your router you need an API pipeline that bypasses the CSRF checks. A default Phoenix project should already have an :api pipeline.

  2. You would then expose a controller through this API pipeline to retrieve a token, e.g.

  scope "/api", MyWeb do
    pipe_through [:api]

    post "/get_token", AuthApiController, :get_token
  end

This wouldn’t include the controllers that expose functionality you want protected behind auth.

  1. Update your :api pipeline to attempt authentication, e.g. by reading a bearer token from the HTTP headers, checking that token, if successful, setting a :current_user assign on the connection. I’m not sure how you do that with phx.gen.auth. Ash Authentication has a load_from_bearer plug that handles most of the mechanics for us.

Our API pipeline looks more or less like:

  pipeline :api do
    plug :accepts, ["json"]
    plug :load_user_from_bearer_token # Try to load user from token
  end
  1. Add an auth check step to the protected routes, e.g.
  scope "/" do
    # The auth check is tacked onto the end of the pipeline
    pipe_through [:api, AuthApiPlug.api_user_required] 

    post "/sensitive_api/secret_thingz", SecretThingController, :create
  end

The AuthApiPlug.api_user_required function plug looks like this:

  def api_user_required(conn, _opts) do
    current_user = conn.assigns[:current_user]

    if is_struct(current_user, User) do
      conn
    else
      payload =
        %{
          errors: [
            %{
              message: "Access denied. Authentication required."
            }
          ]
        }
        |> Jason.encode!()

      conn
      |> put_resp_content_type("application/json")
      |> send_resp(401, payload)
      |> halt()
    end
  end

Hope this at least helps you know what to ask!!

arcanemachine

arcanemachine

I have a project that contains an implementation of what you’re describing:

https://github.com/arcanemachine/phoenix-todo-list

In short, you use the :api pipeline in your router instead of the :browser pipeline so you can bypass the CSRF stuff. Then, you make 2 custom plugs:

  1. A plug to fetch the current API user (based on the bearer token that they pass in the Authorization HTTP header)

  2. A plug or two to fetch the desired resource, and to verify that the user is eligible to access the protected resource.

It’s been a little while since I made this (like a couple months), but I believe I had to implement the bearer token auth myself. It uses the exact same auth token generation scheme as that used by the built-in auth generators, but repackages the values so that they can be delivered over JSON. I dunno, it’s all in the repo, and I documented and tested everything pretty well (no warranties but I’m quite certain I didn’t do anything stupid.).

There’s also an OpenAPI spec and client for it in on the live site for the project (it’s just a todo list CRUD API), so if you’re familiar with those, you can use the online client or import the spec into Postman or Insomnia or whatever. There’s also an Insomnia spec that I used for development which should work (you may need to tweak the environment variables).

It may not be a perfect implementation, but it should have the basics of what you’re looking for. Hope it helps.

EDIT: Looks like I posted pretty much everything that @mindok said :smiley:

codeanpeace

codeanpeace

It’s definitely worth reading through all the code generated by mix phx.gen.auth since it was designed to be very modular and extensible. For example, some of the functions that get added to your auth context could also be re-used in your API auth workflow and/or serve as a starting point for writing API auth-specific code.

Plugs are very much meant to be hand-rolled for encapsulating shared logic. If you haven’t already, check out this section of the Phoenix guides on Plugs as composition.

Last Post!

adw632

adw632

This is also a good explanation on using guardian JWT for API auth.

One thing that is worth paying some attention to is token expiry. Best advice is to keep access tokens very short lived (e.g. 1 minute) and then you don’t need to store JWT’s in a database, look them up or even worry about supporting revocation in most cases.

You can do revocation if 1 minute is too big of a risk in a performant manner and still avoid managing tokens in the database which would then require a database lookup in the fast path and a background process to keep sweeping out the old tokens.

If you really, must do revocation, consider using mnesia for fast lookup and cluster wide state (doesn’t need to persist) or alternatively use ETS to maintain an in memory cache and notify other nodes with phoenix channels (similar to Phoenix sign out here). Only the userid and revocation time needs to be maintained and it only needs to exist over the next minute (or whatever your token expiry period is) to force reauthentication. On initial startup of your app, require all API clients to reauthenticate if their token is older than the start time of the VM, so as to close out a potential hole if the VM restarts within the 1 minute token lifetime.

Which also leads into the typical case where most apps will lookup the user from the database on every API request. This again puts the database in the API fast path which can be quite limiting to overall API performance.

If you want high performance then bundle all the necessary information required to make API access decisions, such as the user id and their role into the JWT (it’s a self contained unforgable data structure) and avoid the cost of database lookups on each API request.

If you have sensitive information you wish to put into the token but not allow the client to observe it then use a JWE (encrypted JWT). Guardian supports that here.

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42716 114
New

We're in Beta

About us Mission Statement