我正在试着测试我的控制器,但是我一直遇到一个“未认证”的卫士错误。我想我知道哪里出了问题,但我只是不确定为什么它不能工作。这是我所拥有的。
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?
发布于 2020-04-18 04:59:57
尽管您没有在问题中指定您的监护版本,但是对于版本~> 2.0,Bearer是verify_header插件的默认领域参数。
您应该替换:
|> put_req_header("authorization", "bearer: " <> jwt)使用
|> put_req_header("authorization", "Bearer " <> jwt)除非使用,否则您使用bearer:显式定义了verify_header插件
plug Guardian.Plug.VerifyHeader, realm: "bearer:"https://stackoverflow.com/questions/49952167
复制相似问题