0

I am updating Guardian from v0.14 to v1.0.

I am following update guide from official guardian github page and I faced one problem.

In order to update, I slightly changed my authentication logic.

From:

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

To:

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

And I got nil from Guardian.Plug.current_resource(conn)... in order to resolve this problem, I store token in front-end localStorage and pass it to get user information.

But I still think that it is better practice to get user information from current_resource. How can I achieve this?

-- EDIT 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
D.R
  • 829
  • 4
  • 16
  • 30
  • Where is `Guardian.Plug.current_resource` called? Is it when you're trying to use your access-token or is it in the same flow up there? It is unclear. I assume you meant when making an authenticated request? – Simon May 07 '18 at 10:54
  • yes, i have a `current_user_controller` which checks whether user is authenticated or not. To check, I use `current_resource` – D.R May 07 '18 at 11:06
  • Then I think you should just try to use what is already built-in. If you haven't seen it, there is a `Guardian.Plug.VerifyHeader` which you can put in your `router.ex` under a scope, say `scope "/api", :authenticated`. So if you write `plug Guardian.Plug.VerifyHeader, realm: "Bearer"` it will look for a header `"Authorization: Bearer "` and fetch it. It will then call your implementation that you supplied in the `config.ex`, calling the callback `resource_from_claims`. I think it may be set to return `nil` by default, and maybe that's why you experience this. Try that and see – Simon May 07 '18 at 11:10

0 Answers0