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

:wave:

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

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
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...
273 38985 115
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement