首页 > 解决方案 > Guardian.Plug.current_resource(conn) 返回 nil

问题描述

我正在将 Guardian 从 更新v0.14v1.0

我正在关注官方监护人 github 页面的更新指南,但遇到了一个问题。

为了更新,我稍微改变了我的身份验证逻辑。

从:

case Myapp.Session.authenticate(session_params) do
  {:ok, user} ->
    {:ok, jwt, _full_claims} = user |> Guardian.encode_and_sign(:token)

    conn
    |> put_status(:created)
    |> render("show.json", jwt: jwt, user: user)

  :error ->
    conn
    |> put_status(:unprocessable_entity)
    |> render("error.json")
end

至:

case Myapp.Session.authenticate(session_params) do
  {:ok, user} ->
    {:ok, jwt, _full_claims} = Core.Guardian.encode_and_sign(user)

    conn
    |> put_status(:created)
    |> render("show.json", jwt: jwt, user: user)

  :error ->
    conn
    |> put_status(:unprocessable_entity)
    |> render("error.json")
end

而我nilGuardian.Plug.current_resource(conn)……为了解决这个问题,我存储token在前端localStorage并通过它来获取用户信息。

但我仍然认为从current_resource. 我怎样才能做到这一点?

- 编辑 current_user_controller.ex

def show(conn, _) do
 user = Myapp.Guardian.Plug.current_resource(conn)

 conn
 |> put_status(:ok)
 |> render("show.json", user: user)
end

标签: authenticationelixirguardian

解决方案


推荐阅读