守护者 - "记住我"使用刷新令牌

时间:2016-09-27 03:58:22

标签: elixir phoenix-framework remember-me refresh-token

我试图在以下GitHub问题中实现@hassox提供的建议:

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

用户登录后,我生成一个令牌并将其存储在一个包含ttl的cookie中:

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 )

另外,我的Guardian.Plug.LoadResource管道中有一个插件(放在:browser_auth下面):

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

这就是插件目前的样子:

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

如何创建新令牌,将其存储在会话中并继续到所需的页面,而不是重新路由到登录页面?

1 个答案:

答案 0 :(得分:2)

我猜代码可能是这样的:

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

在您的管道中,将MyApp.Plug.RememberMe放在VerifySession之前 请试着看看它是如何工作的