Understanding tokens and Phoenix Plug

I’ve been having (too much?) fun building stuff using Phoenix, so I thought I would try to dive into a realm I’ve always been uncomfortable with, authentication. I’ve only really worked on projects that didn’t need auth in the past, so I really feel out of my league… I worked through a pretty great tutorial on passwordless auth using tokens and email verification, but I’m left feeling confused with how the flow works from here.

I see the user is logged in via Phoenix.Token.verify which checks the token it created earlier to ensure that it is still valid. But now what? I feel like I should be making a plug like Myapp.EnsureToken (and hopefully it would be able to fetch the current user data so that I could display their name and such on pages, or maybe I need a Myapp.CurrentUser plug too?) and sticking it in a pipeline like :token_req then scoping pages that I want to have auth with this pipeline. In my mind something like:

# web/router.ex

...

pipeline :token_req do
  plug Myapp.EnsureToken
  plug Myapp.CurrentUser
end

...

scope "/", Myapp do
  pipe_through [:browser]

  get "/signin/:token", SessionController, :show, as: :signin
  resources "/signin", SessionController, only: [:new, :create, :delete]
  resources "/register", UserController, only: [:new, :create]
  resources "/", PageController, only: [:index]

  scope "/verified", Verified, as: :verified do
    pipe_through [:token_req]

    resources "/", PageController, only: [:index]
  end
end
...

Is this the right idea? Or do I somehow not need these things with token (and if not, how does Phoenix know what’s happening with the token)?

If anyone has a good resource, or examples of the right kind of implementation for this kind of thing, I’d appreciate it if you could point me in the right direction. Thanks!

1 Like

I like to use ueberauth/guardian for jwt authentication.

So as I have it now (almost certainly wrong) I use Phoenix.Token to create a token that is sent to the registering user via email in a link. Phoenix.Token then verifies this token when they click the link, whence I use Guardian.Plug.sign_in/2 to sign in the user and then I use the Guardian.Plug.VerifySession and Guardian.Plug.LoadResource plugs to control auth.

This works, in that I can signup and signin succesfully, but I really would like for someone to let me know if this is right. Where does the token disappear to here? Isn’t Guardian just managing browser sessions and not tokens in this case? How do I sort all of this out in my mind?

Also, I think I could have generated and verified the emailed token using Guardian.Plug.encrypt_and_sign and Guardian.Plug.decrypt_and_verify, but I’m not sure what the advantage is of one over the other.

1 Like