Guardian问题 - EnsureAuthenticated不起作用

时间:2018-04-28 18:30:09

标签: authentication elixir jwt phoenix-framework guardian

我正在尝试让Guardian auth为我的应用程序工作。但我完全陷入困境,无法找到任何支持我遇到的问题。

据我所知,我已经准确地设置了Guardian文档如何显示,但是当我在浏览器中测试身份验证时,它在Guardian提供的EnsureAuthenticated插件上失败了。

以下是我正在使用的内容:

CONFIG:

所有值都在应用中正确填充。

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

在此控制器中失败。当它进入EnsureAuthenticated插头时,它就会停在那里。但此时我在标题中有一个有效的JWT。

这是我的参数:

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

我已经确认JWT有效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 => {
       })

同样,问题是我的身份验证在Plug.EnsureAuthenticated挂钩失败了。但是我无法理解为什么因为我似乎正确地设置了一切并且JWT在auth标头中。任何帮助都将非常感谢!!我已经被困在这里很长一段时间了。感谢

1 个答案:

答案 0 :(得分:1)

您将标头作为POST参数发送,而不是HTTP标头。 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)"
  }
})