No referer in req_headers when Guardian calls its error_handler

In my system, when the user visits protected resources, the user is redirected to an OAuth authentication if not signed in. I want to redirect the user back to the original URL (from referer request header?).

I’m using the Guardian library, found the referer is missing.

My config:


  pipeline :ensure_auth do
    plug Guardian.Plug.Pipeline,
      module: EvercamWechatWeb.Guardian,
      error_handler: EvercamWechatWeb.AuthErrorHandler

    plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}
    plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}
    plug Guardian.Plug.EnsureAuthenticated
    plug Guardian.Plug.LoadResource
defmodule EvercamWechatWeb.AuthErrorHandler do
  @behaviour Guardian.Plug.ErrorHandler

  alias EvercamWechatWeb.Router.Helpers, as: Routes

  @impl true
  def auth_error(conn, {_type, _reason}, _opts) do
    referer = Plug.Conn.get_req_header(conn, "referer") # there is no referer in req header
    Phoenix.Controller.redirect(conn, to: Routes.auth_path(conn, :request, :wechat))

Did I miss something? Thanks

Are you setting a referer header? I personally set my return url in the session (and not a URL but rather a routing address in mine, but eh).

I didn’t set an referer header. I suppose if the guardian authentication failed, there should be a referer header available to set in my OAuth redirect uri. Then when the OAuth succeed, I can redirect the user back to where they originally visited.