如果用户发送的令牌未过期,但该特定用户已不存在,
Guardian
仍然让用户访问控制器。
我已添加
{:ok, nil}
在
current_user.ex
它只是简单地终止了连接,我认为这不是正确的方法,因为我需要向用户返回一些东西,比如一个错误。我不确定我应该在那里用什么?
这是我的路由器:
pipeline :authed_api do
plug :accepts, ["json"]
plug Guardian.Plug.VerifyHeader, realm: "Bearer"
plug Guardian.Plug.EnsureAuthenticated, handler: Web.GuardianErrorHandler
plug Guardian.Plug.LoadResource
plug Web.CurrentUser, handler: Web.GuardianErrorHandler
end
scope "/api/v1", Web do
pipe_through :authed_api
get "/logout", UserController, :logout
resources "/users", UserController
get "/*get", ErrorController, :handle_redirect
end
这是我的
current_user
defmodule Web.CurrentUser do
import Plug.Conn
import Guardian.Plug
import Web.GuardianSerializer
def init(opts), do: opts
def call(conn, _opts) do
current_token = Guardian.Plug.current_token(conn)
case Guardian.decode_and_verify(current_token) do
{:ok, claims} ->
case Web.GuardianSerializer.from_token(claims["sub"]) do
{:ok, nil} ->
conn = Plug.Conn.halt(conn) # <-this line, I was referring to
{:ok, user} ->
Plug.Conn.assign(conn, :current_user, user)
{:error, _reason} ->
conn
end
{:error, _reason} ->
conn
end
end
end
提前谢谢你。