Phoenix GraphQL Tutorial with Absinthe: Authentication with Guardian

I can’t get the authorization to work, I get a token successfully:

But when I do a query with the token it returns unauthorized

I have no idea what is going on, and my files seem to be the same as yours (with some caveats, like encrypted_password instead of password_hash)

Here is the plug

defmodule Vulkan.Web.Context do
  @behaviour Plug
 
  import Plug.Conn
 
  def init(opts), do: opts
 
  def call(conn, _) do
    case Guardian.Plug.current_resource(conn) do
      nil -> conn
      user ->
        put_private(conn, :absinthe, %{context: %{current_user: user}})
    end
  end
end

The router

defmodule Vulkan.Router do
  use Vulkan.Web, :router

  pipeline :api do
    plug :accepts, ["json"]
  end
  
  pipeline :graphql do
    plug Guardian.Plug.VerifyHeader, realm: "Bearer"
    plug Guardian.Plug.LoadResource
    plug Vulkan.Web.Context
  end

  scope "/api" do
    pipe_through :graphql
    
    forward "/", Absinthe.Plug,
      schema: Vulkan.Schema
  end

  forward "/graphiql", Absinthe.Plug.GraphiQL,
    schema: Vulkan.Schema

end

The post resolver

defmodule Vulkan.PostResolver do
  alias Vulkan.{ Repo, Post }
  import Ecto.Query, only: [where: 2]
  
  def all(_args, %{context: %{current_user: %{id: id}}}) do
    posts =
      Post
      |> where(user_id: ^id)
      |> Repo.all
   
    {:ok, posts}
  end
  
  def all(_args, _info) do
    {:error, "Unauthorized"}
  end
end

The session model

defmodule Vulkan.Session do
  alias Vulkan.User
 
  def authenticate(params, repo) do
    user = repo.get_by(User, email: String.downcase(params.email))
    case check_password(user, params.password) do
      true -> {:ok, user}
      _ -> {:error, "Incorrect login credentials"}
    end
  end
 
  defp check_password(user, password) do
    case user do
      nil -> false
      _ -> Comeonin.Bcrypt.checkpw(password, user.encrypted_password)
    end
  end
end

I have no idea of why it doesn’t work, being the same codebase it should, any ideas?

EDIT I’m pretty dumb, was doing requests to /graphql instead of /api :laughing:

1 Like