2

这种情况的延续:Can't understand destructuring in JWT auth (Phoenix)

我正在使用 JWT 和 Guardian 和 Comeonin 设置 API 身份验证。这个动作似乎有效,因为user从 iex 调用 a 并将其传递Guardian.encode_and_sign/2给我正在寻找的元组。

  def create(conn, %{"session" => session_params}) do
    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
  end

当我发出 curl 请求时,我在控制台中收到此错误:

[error] #PID<0.565.0> running MyApp.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /api/v1/sessions
** (exit) an exception was raised:
    ** (Poison.EncodeError) unable to encode value: {nil, "users"}
        (poison) lib/poison/encoder.ex:383: Poison.Encoder.Any.encode/2
        (poison) lib/poison/encoder.ex:227: anonymous fn/4 in Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:227: anonymous fn/4 in Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:227: anonymous fn/4 in Poison.Encoder.Map.encode/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map."-encode/3-lists^foldl/2-0-"/3
        (poison) lib/poison/encoder.ex:228: Poison.Encoder.Map.encode/3
        (poison) lib/poison.ex:41: Poison.encode!/2
        (phoenix) lib/phoenix/controller.ex:740: Phoenix.Controller.do_render/4
        (myapp) web/controllers/api/v1/sessions_controller.ex:1: MyApp.SessionsController.action/2

我应该寻找什么来解决这个问题?

4

1 回答 1

3

看看这个问题

您正在将私有元数据信息编码到客户端。

但是,属性Poison中有一个 :except 选项@derive,它可以从编码结果中排除一个键:

defmodule User do
  @derive {Poison.Encoder, except: [:__meta__]}
end
于 2017-08-22T21:25:28.617 回答