rlipscombe
Plug: Per-route authentication
I’m using plug (without Phoenix), and I’ve got a router that contains something like the following:
get "/users/:user_id/favorites" do
body = get_favorites(user_id)
send_resp(conn, 200, body)
end
I’d like to use JWT to restrict access to this route based on :user_id, but using a secret associated with :user_id.
Using Guardian (or, more directly, using Joken), I can implement JWT checking for the entire application, but I can’t figure out how to attach authentication “middleware” to this route and get hold of the value of :user_id.
Any pointers?
First Post!
idi527
![]()
You can put your auth logic in a plug and route the requests that need to be authenticated via it.
One way to do it is by adding an extra “authenticated” router plug.
defmodule YourApp.MainRouter do
use Plug.Router
plug :match
# ...
plug :dispatch
get "/" do
send_resp(conn, 200, "all unauthenticated requests can be handled in this router")
end
forward "/users", to: YourApp.AuthedRouter
end
defmodule YourApp.AuthedRouter do
use Plug.Router
plug :match
plug YourApp.AuthPlug
plug :dispatch
get "/:user_id/favorites" do
body = get_favorites(user_id)
send_resp(conn, 200, body)
end
end
But if you don’t have many routes that need to be authenticated, you can put the “whether to authenticate?” logic into the authenticating plug itself.
defmodule YourApp.AuthPlug
@behaviour Plug
def init(opts), do: opts # maybe list the routes that need to be authenticated in opts
def call(%{path_info: ["users" | _rest]}, _opts) do
# authenticate
end
def call(conn, _opts) do
# don't authenticate
conn
end
end
Last Post!
victorolinasc
You can look at how we’ve implemented this plug (it is a single source file) here.
Since our implementation isn’t flexible enough for your use case, you can use it as a baseline if you want to keep a single router (though @idi527’s anwer would work just as well). Specifically, on this line you can fetch the path from the conn since it already matched.
Hope this helps.
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









