Placing Guardian markers inside cookies and reading them from there

I have an application that uses JWT authentication with Guardian . When a user logs in, the response contains jwt in the body. The interface (which is SPA) then stores this jwt in localStorage and attaches it to the header of Authorizationevery request sent from there. The server then verifies this using the Guardian built-in validation buffer:

pipeline :api do
  plug :accepts, ["json"]
  plug Guardian.Plug.VerifyHeader, realm: "Bearer"
end

I would like to change this so that instead of storing the JWT in localStorage (which is unsafe) the server sends them to the interface as secure cookies (with Secureand settings HttpOnly), then I want the Guardian to read jwt from the cookie, and not from the header Authorization.

Does Guardian support this functionality?

Here is my SessionController function create:

def create(conn, params) do
  case authenticate(params) do
    {:ok, user} ->
      new_conn = Guardian.Plug.api_sign_in(conn, user, :access)
      jwt = Guardian.Plug.current_token(new_conn)

      new_conn
      |> put_status(:created)
      |> render("show.json", user: user, jwt: jwt)
    :error ->
      conn
      |> put_status(:unauthorized)
      |> render("error.json")
  end
end
+6
source share
2 answers

Just use encrypted session cookies. JWT points are not intended to be stored locally (in localStorage or in a cookie) because you are simply giving up the benefits of what the JWT was for.

From your piece of code, it looks like you are using JWT tokens as a substitute for session cookies. Why not just use session cookies?

0
source

, , JWT. , . JWT / . . , , FE SK

0

Source: https://habr.com/ru/post/1672300/


All Articles