Guardian Auth - User is successfully authenticated, but not stored in conn after redirect

I am building my first Elixir app using Guardian and I am having an issue where a User can log in and be authenticated, but upon redirect to the next page the conn no longer stores the user information and Guardian.Plug.is_authenticated? returns false.

session_controller.ex

  ....
  def create(conn, %{"session" => %{"email" => email, "password" => password}}) do
    case PhoenixApp.Auth.authenticate_user(email, password) do
      {:ok, user} ->
        conn
        |> PhoenixApp.Auth.login(user)
        |> put_flash(:info, "Welcome back!")
        |> redirect(to: "/users")

      {:error, _reason} ->
        conn
        |> put_flash(:error, "Invalid username or password.")
        |> render("new.html")
    end
  end
  ...

router.ex

  ...
  scope "/", PhoenixAppWeb do

  pipe_through [:browser, :auth]

    get "/", PageController, :index

    get "/signup", UserController, :new
    resources "/users", UserController, except: [:new]

    get "/login", SessionController, :new
    post "/login", SessionController, :create
    delete "/logout/:id", SessionController, :delete
  end

  # Auth pipeline
  pipeline :auth do
    plug(PhoenixApp.Auth.AuthAccessPipeline)
  end
  ...

auth.ex

  ...
  def login(conn, user) do
   conn
    |> Guardian.Plug.sign_in(user)
    |> assign(:current_user, user)
    |> IO.inspect
    |> put_user_token(user)
  end
  ...

auth_access_pipeline.ex

defmodule PhoenixApp.Auth.AuthAccessPipeline do
  @moduledoc false

  use Guardian.Plug.Pipeline,
    otp_app: :phoenix_app,
    error_handler: PhoenixApp.Auth.AuthErrorHandler

  plug(Guardian.Plug.Pipeline,
    module: PhoenixApp.Guardian,
    error_handler: PhoenixApp.Auth.AuthErrorHandler
  )

  # commented out plugs or else will be invalid token error 
  # plug(Guardian.Plug.VerifySession, claims: %{"typ" => "access"})
  # plug(Guardian.Plug.EnsureAuthenticated)
  # plug(Guardian.Plug.LoadResource)
end

The IO.inspect(conn) from my login method returns a JSONified User struct for the user that just signed in in the assigns key under current_user, and also stores a user_token with a token. If you inspect the conn after redirect to /users, the current_user in assigns is nil and there is no user_token.

:wave:

What happens there?

Updated original post to show code

You might want to give Pow a chance where all this is plug and play, you can even use guardian for JWT if thats what you after.

1 Like