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
- use mix phx.gen.secret to
- add an API key table with the user ID as a foreign key
- build my own plug to check the API key
- 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
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:
-
In your router you need an API pipeline that bypasses the CSRF checks. A default Phoenix project should already have an
:apipipeline. -
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.
- Update your
:apipipeline to attempt authentication, e.g. by reading a bearer token from the HTTP headers, checking that token, if successful, setting a:current_userassign on the connection. I’m not sure how you do that withphx.gen.auth. Ash Authentication has aload_from_bearerplug 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
- 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
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:
-
A plug to fetch the current API user (based on the bearer token that they pass in the
AuthorizationHTTP header) -
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 ![]()
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
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









