无法理解JWT auth(凤凰城)的解构

时间:2017-08-22 19:20:44

标签: authentication elixir jwt phoenix-framework destructuring

我正在设置一个模式,我在凤凰城看到了一些用于API身份验证的地方,使用Comeonin和Guardian进行JWT身份验证。

当我从CURL发布到MyApp.SessionsController.create/2时,我会收到来自user的{​​{1}}回复,正如我所料。但是,我应该将它解构为MyApp.Session.authenticate/1,然后可以将其传送到Guardian。我使用{:ok, jwt, _full_claims}查看IO.inspect user对象并收到以下错误:

终端:

user

当我在IEX curl -H "Content-Type: application/json" -X POST -d '{"email":"me@myapp.com","password":"password", "session":{"email":"mark@myapp.com", "password":"password"}}' http://localhost:4000/api/v1/sessions IO.inspect时,我看到了这一点:

user

我看到了这个错误:

%MyApp.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, avatar_url: nil,
 email: "me@myapp.com", handle: "me", id: 2,
 inserted_at: ~N[2017-08-22 18:26:10.000033], password: nil,
 password_hash: "$2b$12$LpJTWWEEUzrkkzu2w9sRheGHkh0YOgUIOkLluk05StlmTP6EiyPA6",
 updated_at: ~N[2017-08-22 18:26:10.007796]}

这究竟是什么意思:Request: POST /api/v1/sessions ** (exit) an exception was raised: ** (MatchError) no match of right hand side value: %MyApp.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, avatar_url: nil, email: "me@myapp.com", handle: "mark", id: 2, inserted_at: ~N[2017-08-22 18:26:10.000033], password: nil, password_hash: "$2b$12$LpJTWWEEUzrkkzu2w9sRheGHkh0YOgUIOkLluk05StlmTP6EiyPA6", updated_at: ~N[2017-08-22 18:26:10.007796]} (myapp) web/controllers/api/v1/sessions_controller.ex:11: MyApp.SessionsController.create/2

以下是设置:

{:ok, jwt, _full_claims} = user
# mix.exs
  defp deps do
    [
      {:distillery, "~> 1.4", runtime: false},
      {:phoenix, "~> 1.3.0-rc", override: true},
      {:phoenix_ecto, "~> 3.2"},
      ...
      {:comeonin, "~> 4.0"},
      {:bcrypt_elixir, "~> 0.12.0"},
      {:guardian, "~> 0.14.5"},
]
# web/router.ex
  ...
  pipeline :api do
    plug :accepts, ["json"]
    plug Guardian.Plug.VerifyHeader
  end

  scope "/api", MyApp do
    pipe_through :api

    scope "/v1" do
      post "/sessions", SessionsController, :create
    end
  end
...
# web/controllers/session_controller.ex
defmodule MyApp.SessionsController do  
  use MyApp.Web, :controller

  alias MyApp.{Repo, User}

  plug :scrub_params, "session" when action in [:create]

  def create(conn, %{"session" => session_params}) do
    case MyApp.Session.authenticate(session_params) do
    {:ok, user} ->
      {:ok, jwt, _full_claims} = user
        IO.inspect user       # Trying to test it here 
        |> 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
# web/services/session.ex
defmodule MyApp.Session do 

  alias MyApp.{Repo, User}
  import Bcrypt

  def authenticate(%{"email" => email, "password" => password}) do
    case Repo.get_by(User, email: email) do
      nil -> 
        :error
      user ->
        case verify_password(password, user.password_hash) do
          true ->
            {:ok, user}
          _ ->
            :error
        end
    end
  end

  defp verify_password(password, pw_hash) do
    Comeonin.Bcrypt.checkpw(password, pw_hash)
  end
end

编辑:添加卫报信息

# lib/MyApp/User.ex
defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    field :email, :string
    field :handle, :string
    field :password_hash, :string
    field :avatar_url, :string
    field :password, :string, virtual: true

    timestamps
  end

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, [:email, :handle, :password_hash, :password, :avatar_url])
    |> validate_required([:email])
    |> validate_length(:email, min: 1, max: 255)
    |> validate_format(:email, ~r/@/)
  end
#config/config.exs
config :guardian, Guardian,
  issuer: "MyApp",
  ttl: { 30, :days},
  verify_issuer: true,
  secret_key: "abc123",
  serializer: MyApp.GuardianSerializer

1 个答案:

答案 0 :(得分:1)

{:ok, jwt, _full_claims}是通过调用Guardian.encode_and_sign(user, :token)返回的值。这是您链接到的教程中的原始代码:

{:ok, jwt, _full_claims} = user 
  |> Guardian.encode_and_sign(:token)

与:

相同
{:ok, jwt, _full_claims} = Guardian.encode_and_sign(user, :token)

另一方面,您的代码执行{:ok, jwt, _full_claims} = user,下一行是新语句。如果您想检查用户并仍然执行本教程所做的操作,您可以执行以下操作:

{:ok, jwt, _full_claims} = user
  |> IO.inspect
  |> Guardian.encode_and_sign(:token)

IO.inspect会返回打印后传递的值,因此此代码的功能与教程完全相同,只是它会打印user的值。< / p>