1

我正在尝试在以下 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中有一个 Plug(放在下面) ::browser_auth

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

这是 Plug 目前的样子:

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

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

4

1 回答 1

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 请尝试看看它是如何工作的

于 2016-10-03T13:30:42.093 回答