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.
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








