简体   繁体   中英

Guardian - “Remember Me” using refresh token

I'm trying to implement the advice given by @hassox in the following GitHub issue:

https://github.com/ueberauth/guardian/issues/142

After the user logs in, I'm generating a token and storing it in a cookie that has a ttl:

claims = Guardian.Claims.app_claims
|> Guardian.Claims.ttl({30, :days})

{:ok, token, full_claims } = Guardian.encode_and_sign(user, :remember, claims)

thirty_days = 86400 * 30

conn = put_resp_cookie(conn, "remember_me", token, max_age: thirty_days )

In addition, I have a Plug (to put underneath Guardian.Plug.LoadResource ) in my :browser_auth pipeline:

pipeline :browser_auth do
  plug Guardian.Plug.VerifySession
  plug Guardian.Plug.LoadResource
  plug Zoinks.Plug.RememberMe
end

Here's what the Plug looks like at the moment:

defmodule Zoinks.Plug.RememberMe do
  import Plug.Conn
  import Guardian.Plug

  def init(opts \\ %{}), do: Enum.into(opts, %{})

  def call(conn, opts) do
    current_user = current_resource(conn)

    if ( current_user == nil ) do
      jwt = conn.req_cookies["remember_me"]

      case Guardian.decode_and_verify(jwt) do
        { :ok, claims } ->
          if ( claims |> Map.get("typ") == "remember" ) do
            {:ok, remember_user } = load_resource( conn, claims, opts )

            # This doesn't seem to do what I want
            conn |> Guardian.Plug.sign_in( remember_user )
          end

        { :error, reason } ->
          # Do something
      end
    end
  end
end

How do I create a new token, store that in the session and continue on to the desired page, instead of being re-routed to the sign-in page?

I guess the code could be like this:

defmodule MyApp.Plug.RememberMe do
  import Plug.Conn
  import Guardian.Plug

  def init(opts \\ %{}), do: Enum.into(opts, %{})

  def call(conn, _) do
    current_user = current_resource(conn)

    if ( current_user == nil ) do
      jwt = conn.req_cookies["remember_me"]
      case Guardian.decode_and_verify(jwt) do
        { :ok, claims } ->
          the_key = Map.get(claims, :key, :default)
          put_session(conn, Guardian.Keys.base_key(the_key), jwt)
      end
    end
  end
end

And in your pipeline, put your MyApp.Plug.RememberMe before VerifySession Please try and see how it works 👍

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM