【问题标题】:API Authentication Test with Guardian使用 Guardian 进行 API 身份验证测试
【发布时间】:2018-04-21 03:46:22
【问题描述】:

我正在尝试测试我的控制器,但我一直遇到监护人“未经身份验证”错误。我想我知道哪里出了问题,但我只是不确定为什么它不起作用。这是我所拥有的。

  setup %{conn: conn} do
    user = insert(:user)
    {:ok, jwt, _} = Guardian.encode_and_sign(user, :api)
    conn = conn
    |> put_req_header("accept", "application/json")
    |> put_req_header("authorization", "bearer: " <> jwt)

    {:ok, conn: conn}
  end

  test "creates and renders resource when data is valid", %{conn: conn} do
    conn = post(conn, league_path(conn, :create), league: @valid_attrs)
    body = json_response(conn, 201)
    assert body["name"]
    assert Repo.get_by(League, name: "Obama's League")
  end

这是正确地创建和签署 JWT,但由于某种原因它没有在路由器中对其进行身份验证。这是路由器。

pipeline :authenticated do
  plug(Guardian.Plug.EnsureAuthenticated)
end

scope "/api/v1", Statcasters do
  pipe_through([:api, :authenticated])

  resources("/leagues", LeagueController, only: [:create])
end

我认为这是我出错的地方,因为文档显示如果未解决此路由器插件,则会出现此错误:

错误:

** (RuntimeError) expected response with status 201, got: 401, with body:
     {"errors":["Unauthenticated"]}
     code: body = json_response(conn, 201)

如何在控制器测试中成功使用 Guardian?

【问题讨论】:

  • pipe_through([:authenticated, :api]) 不行吗?插件的顺序很重要,你所拥有的东西会在 api plug before 进行身份验证。
  • 很高兴知道这一点。但是,如果我切换顺序,我仍然会得到相同的结果。
  • 也许你不应该直接在 :authenticated 管道中使用插件。也许你应该建立一个监护人管道并使用它。来自文档“所有插头都需要在管道中”hexdocs.pm/guardian/readme.html#plugs

标签: elixir phoenix-framework guardian


【解决方案1】:

虽然您没有在问题中指定您的监护人版本,但对于版本~&gt; 2.0Bearerverify_header 插件的默认领域参数。

你应该替换:

|> put_req_header("authorization", "bearer: " <> jwt)

|> put_req_header("authorization", "Bearer " <> jwt)

除非您使用bearer: 明确定义了verify_header 插头

 plug Guardian.Plug.VerifyHeader, realm: "bearer:"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 2020-12-08
    • 2016-05-05
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    相关资源
    最近更新 更多