Search code examples
authenticationelixirjwtphoenix-frameworkguardian

Issue with Guardian - EnsureAuthenticated not working


I'm attempting to get Guardian auth work for my application. But I'm completely stuck and can't find any support for the problem I'm having.

As far as I know I've setup Guardian exactly how the documentation shows how, but when I test authentication in the browser it fails on EnsureAuthenticated plug that Guardian provides.

Here is what I'm working with:

CONFIG:

All values are filled correctly in the app.

config :statcasters, MyApp.Guardian,
  allowed_algos: ["HS512"],
  verify_module: Guardian.JWT,
  issuer: "my_app",
  ttl: {30, :days},
  allowed_drift: 2000,
  verify_issuer: true,
  secret_key: "my_secret_key"

AUTHENTICATED CONTROLLER:

defmodule Statcasters.LeagueController do
  use StatcastersWeb, :controller
  alias Statcasters.{League, Repo}

  plug Guardian.Plug.EnsureAuthenticated

  def create(conn, %{"league" => league_params}) do
    changeset = League.changeset(%League{}, league_params)

    case Repo.insert(changeset) do
      {:ok, league} ->
        conn
        |> put_status(:created)
        |> render("league.json", league: league)

      {:error, changeset} ->
        conn
        |> put_status(:unprocessable_entity)
        |> render(Statcasters.ChangesetView, "error.json", changeset: changeset)
    end
  end
end

In this controller is where it fails. When it goes to the EnsureAuthenticated plug it halts right there. but I have a valid JWT in the headers at this point.

Here our my params:

Parameters: %{"headers" => %{"Authorization" => "Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJTdGF0Y2FzdGVycyIsImV4cCI6MTUyNzUzMDA1OSwiaWF0IjoxNTI0OTM4MDU5LCJMiOiJTdGF0Y2FzdGVycyIsImp0aSI6IjJhNDg3MWQ4LTkwZGEtNDNlYS1hMGJlLWVjNjgwNjIzOTBkOCIsIm5iZiI6MTUyNDkzODA1OCwic3ViIjoiMSIsInR5cCI6InJlZnJlc2gifQ.EKeaHoQiW9tmtsabPIjj6069zD6Vcex9w3xfkXP5MIyiogWh400S6wMzaAsTQd20I5ai_y9jJTtgLzqYfbGTaQ"}

I've verified that the JWT is valid here.

REQUEST:

       axios.post('/api/v1/leagues', {
          league: {
            name: this.$refs.league_name.value,
            player_limit: this.$refs.player_limit.value,
          },
          headers: {
            Authorization: "Bearer jwt(correct jwt)"
          }
        }).then(response => {
        }).catch(error => {
       })

Again, the problem is that my auth is failing in the Plug.EnsureAuthenticated hook. But I can't understand why because I seem to be setting everything up correctly and the JWT is in the auth header.


Solution

  • You're sending the header as a POST parameter, not an HTTP header. You need to put the headers in the third argument for axios.post:

    axios.post('/api/v1/leagues', {
      league: {
        name: this.$refs.league_name.value,
        player_limit: this.$refs.player_limit.value,
      }
    }, {
      headers: {
        Authorization: "Bearer jwt(correct jwt)"
      }
    })