rlipscombe

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

idi527

:waving_hand:

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

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
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
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement