我正在为注册/登录创建一个 API。我正在使用监护人“~> 1.0”为我的注册生成一个 jwt 令牌。现在,当我在我的文件夹结构中创建一个监护模块时,我将在代码中向您展示。我还在我的 cofig.ex 中传递了密钥。
如果您需要任何其他信息,请告诉我。
现在,当我尝试在我的邮递员端点中传递它时,它给了我一个错误
{
"user": {
"email": "siddhant24333@gmail.com",
"password": "Radiohead",
"password_confirmation": "Radiohead"
}
}
user_controller.ex
def create(conn, %{"user" => user_params}) do
with {:ok, %User{} = user} <- Accounts.create_user(user_params),
{:ok, token, _claims} <- Guardian.encode_and_sign(user) do
conn |> render("jwt.json", jwt: token)
end
end
监护人.ex
defmodule DailyployApi.Guardian do
use Guardian, otp_app: :dailyploy_api
def subject_for_token(user, _claims) do
sub = to_string(user.id)
{:ok, sub}
end
def subject_for_token(_, _) do
{:error, :reason_for_error}
end
def resource_from_claims(claims) do
id = claims["sub"]
resource = DailyployApi.Accounts.get_user!(id)
{:ok, resource}
end
def resource_from_claims(_claims) do
{:error, :reason_for_error}
end
end
这是我尝试生成令牌时遇到的错误
[error] #PID<0.554.0> running DailyployApiWeb.Endpoint (connection #PID<0.553.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/v1/sign_up
** (exit) an exception was raised:
** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: {:error, :secret_not_found}
(dailyploy_api) lib/dailyploy_api_web/controllers/user_controller.ex:1: DailyployApiWeb.UserController.phoenix_controller_pipeline/2
(phoenix) lib/phoenix/router.ex:280: Phoenix.Router.__call__/2
(dailyploy_api) lib/dailyploy_api_web/endpoint.ex:1: DailyployApiWeb.Endpoint.plug_builder_call/2
(dailyploy_api) lib/plug/debugger.ex:122: DailyployApiWeb.Endpoint."call (overridable 3)"/2
(dailyploy_api) lib/dailyploy_api_web/endpoint.ex:1: DailyployApiWeb.Endpoint.call/2
(phoenix) lib/phoenix/endpoint/cowboy2_handler.ex:33: Phoenix.Endpoint.Cowboy2Handler.init/2
(cowboy) /Users/sid/dailyploy_api/deps/cowboy/src/cowboy_handler.erl:41: :cowboy_handler.execute/2
(cowboy) /Users/sid/dailyploy_api/deps/cowboy/src/cowboy_stream_h.erl:296: :cowboy_stream_h.execute/3
(cowboy) /Users/sid/dailyploy_api/deps/cowboy/src/cowboy_stream_h.erl:274: :cowboy_stream_h.request_process/3
(stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
此外,它显示了这个
POST /api/v1/sign_up
[debug] Processing with DailyployApiWeb.UserController.create/2
Parameters: %{"user" => %{"email" => "siddhant24333@gmail.com", "password" => "[FILTERED]", "password_confirmation" => "[FILTERED]"}}
Pipelines: [:api]
[debug] QUERY OK db=60.3ms queue=4.4ms
INSERT INTO "users" ("email","password_hash","inserted_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" ["siddhant24333@gmail.com", "$2b$12$H7f/ZygnxOzjlxMvT/FUr.pcHiMaPR.mp1WrhyLlfznZ.jWVbk0Dq", ~N[2019-07-08 11:30:59], ~N[2019-07-08 11:30:59]]
配置文件
config :dailyploy_api, DailyployApi.Guardian,
issuer: "dailyploy_api",
secret: "eXCQ6ZYZlPkS0p0eOoLLfkEoi0rn6O6pQ0PmhDjbElrc9G9RMQgnCMk+3kw0FHE7"