我在Absinthe中使用内置的GraphiQL接口。如下:
pipeline :browser do
plug RemoteIp, headers: ~w[x-forwarded-for], proxies: ~w[]
plug :accepts, ["html", "json"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
scope "/graphiql" do
pipe_through :browser # Use the default browser stack
forward "/", Absinthe.Plug.GraphiQL,
schema: ApiWeb.Schema,
default_headers: {__MODULE__, :graphiql_headers},
context: %{pubsub: ApiWeb.Endpoint}
end
def graphiql_headers(conn) do
%{
"X-CSRF-Token" => Plug.CSRFProtection.get_csrf_token(),
}
end
我需要最终用户在接口中插入Authentication: Bearer <JWT>
,然后需要为sub:header打开它,其中包含我的用户ID,我需要在解析器中使用它。
用户可以配置自定义标头,这没问题。如果他然后执行GraphSQL查询,接口将向/ graphiql端点发出POST。它位于这个点我想调用一些检查JWT并检索用户信息的插件。
我以为我可以使用default_headers选项,但这似乎只能在GET请求期间调用。
似乎我需要不同的管道用于GET和POST到/ graphiql端点,我该如何实现呢?我一定做错了......
请注意,如果我使用相同的GET和POST管道,则只需访问浏览器中的端点即可检查JWT,这是我不想要的。
答案 0 :(得分:1)
是的,实际上我做了以下事情:
pipeline :authenticate_on_post_only do
plug ApiWeb.Plugs.Authenticate, post_only: true
end
scope "/graphiql" do
pipe_through [:browser, :authenticate_on_post_only]
forward "/", Absinthe.Plug.GraphiQL,
schema: ApiWeb.GraphQL,
socket: ApiWeb.GraphQLSocket
end
结合:
defmodule ApiWeb.Plugs.Authenticate do
use Plug.Builder
alias ApiWeb.Helpers.JWT
plug Joken.Plug, verify: &JWT.verify/0, on_error: &JWT.error/2
plug ApiWeb.Plugs.Subject
plug Backend.Plug.Session
def call(%Plug.Conn{method: "POST"} = conn, opts) do
conn = super(conn, opts) # calls the above plugs
put_private(conn, :absinthe, %{context: conn}) # for absinthe (GraphQL), for resolvers to re-use
end
def call(conn, opts) do
if opts[:post_only] do
conn
else
super(conn, opts) # calls the above plugs
end
end
end
当然,您可以使用任何自己的身份验证插件,而不是我列出的身份验证插件。
我在同一个模块中也有一个REST API,我使用如下:
scope "/v1", ApiWeb do
pipe_through :api
<my resources here>
done
将api管道定义为:
pipeline :api do
plug :put_resp_content_type, "application/json"
plug :accepts, ["json"]
plug ApiWeb.Plugs.Authenticate
end
将对任何类型的HTTP请求进行身份验证。