Hello fellow Alchemists!
I’ve been struggling with Guardian (https://github.com/ueberauth/guardian) for the last few days, I can’t manage to sign in using the Guardian.Plug.sign_in(conn, resource) – which should be so simple!
It feels that I’m missing something really obvious, but I can’t see it. Therefore, l put all my hope to you guys
The problem:
Guardian.Plug.EnsureAuthenticated says that all sessions are unauthenticated, including sessions authenticated with Guardian.Plug.sign_in(conn, resource).
Below are the relevant part of my controller that authenticates the user:
def callback(%{assigns: %{ueberauth_auth: auth}, _params) do
{:ok, user_info} = User.extract_user_info(auth)
case MyApp.User.find_user(user_info.email) do
{:ok, user} ->
conn
|> MyApp.Guardian.Plug.sign_in(user)
|> redirect(to: "/backoffice")
{:error, _} ->
conn
|> put_status(401)
|> render(MyApp.ErrorView, "401.json-api")
end
end
I do find a user and is redirected to /backoffice. The route /backoffice is proteced by Guardian.Plug.EnsureAuthenticated, and every attempt to reach the route fails due to “:unauthenticated”.
If I check the connection with authenticated? in the callback function it says that it is indeed authenticated, like so:
conn = MyApp.Guardian.Plug.sign_in(user)
MyApp.Guardian.Plug.authenticated? conn # true
conn
|> redirect(to: "/backoffice")
The server response from /callback doesn’t seem to include any authentication cookie/header (not sure what I should be looking for).
Any idea what could be wrong? Something that could point me in the right direction would be highly appreciated.
Pipelines
pipeline :maybe_browser_auth do
plug Guardian.Plug.VerifySession
plug Guardian.Plug.LoadResource, allow_blank: true
end
pipeline :ensure_authed_access do
plug MyApp.Guardian.AuthPipeline
end
# MyApp.Guardian.AuthPipeline
defmodule MyApp.Guardian.AuthPipeline do
use Guardian.Plug.Pipeline,
otp_app: :myapp,
module: MyApp.Guardian,
error_handler: MyApp.Guardian.AuthErrorHandler
# Also tested
# Guardian.Plug.VerifyHeader
# Guardian.Plug.VerifyCookie
plug Guardian.Plug.VerifySession
plug Guardian.Plug.EnsureAuthenticated
end
Versions:
{:ueberauth, "~> 0.4"},
{:ueberauth_google, "~> 0.7"},
{:guardian, "~> 1.0"},
Config:
# Guardian configuration
config :myapp, MyApp.Guardian,
issuer: "MyApp",
ttl: { 30, :days },
secret_key: "secret_key"