Is it possible to use Session Authentification with Absinthe?

I currently setup an GraphQl Phoenix Web Server which needs to have an Authentification System which should be Session based. My personal Preference is to choose GraphQL over REST so I used Absinthe for this.

I somehow found out about how Session based Authentifcation is working in Phoenix via adding Values to the Session and return its ìd to the Client.

But what I am curious about is while I can use Plugs to get the Session Id and more and add it to Absinthe Context, I don’t know how to add the User Id to the Session after a User is logged in (because I have no access to the conn in the Resolver.

Anyone has an Idea how to solve this?

Welcome!

This is achieved with a plug you write that goes prior to Absinthe.Plug to pull values off of the conn and add them to the Absinthe context: See: The Context and Authentication — absinthe v1.6.3 That particular example uses a header, but you can pull values from the session there too.

4 Likes

Sure the Issue is that I can’t modify the session from an GraphQL Resolver so I cannot achieve login (storing user_id in session). So I had to create some REST Endpoints for that. But thanks for your help :slight_smile: This was just me to want everything nice and consistent :smiley:

You can most certainly write to session, look up the guides to set cookies eith middleware, same procedure.

Our backends have only one GET endpoint, and thats for the lb healthcheck :slight_smile:

2 Likes

Yes as @OliverMT notes, Absinthe.Plug provides a mechanism for setting the session based on the resolver result: Absinthe.Plug — absinthe_plug v1.5.5

2 Likes

Thank you Ben. This is really what I searched for :slight_smile: So maybe you can provide a good source how to handle authentification in a Plug with Absinthe as well? I thought about using a Plug and asking if query/mutation/subscription x is called search for user id in session if it not exists and should raise an error, else do nothing.

I somehow already have this:

defmodule BackendWeb.Plugs.CheckAuthentification do
  import Plug.Conn

  def init(default), do: default

  def call(conn, _default) do
    case get_session(conn, :current_user_id) do
      nil ->
        raise BackendWeb.Exceptions.SessionUser, message: "No User authentificated"

      _ ->
        conn
    end
  end
end

My Issue is that I don’t know how to get the Query name without parsing the whole body myself.

Alright Ben just one little additional Question. I can’t find a way to update the Absinthe.Blueprint Object which the user_id should be placed in. Just found the Absinthe.Resolver.put_result(res, result) method but I am not sure if this is the correct one. It seems more like it is an fancy way to return the response values of the query.

@willey3x37 hey Willey, have you managed to get this working? I am currently going through the exact same pain, getting the sessions to work with a login mutation