Absinthe subscription + Websocket + Auth Token + ApolloClient HOWTO?

I need to be able to add an auth token after the connection has already been made
(Websocket connection params <- Auth token). How to correctly handle subscriptions
when someone subscribes as non authenticated user and after he loges in?.
How to restart Apollo connection (@absinthe/socket-apollo-link) with new connection params?

HTTP Request:

mutation {
  login(username: “foo”, password: “bar”) {
    token
  }
}

channels/user_socket.ex:

  # Client sends token without "Bearer ". 
  # ws://localhost:4000/socket?token=hello
  def connect(%{"token" => token} = _params, socket, _connect_info) do
    IO.inspect token
    case c = gen_context(token) do
      %{current_user: _} ->
        socket = Absinthe.Phoenix.Socket.put_options(socket, context: c)
        {:ok, socket}
      _ -> :error
    end
  end

  def connect(_params, _socket, connect_info) do
    IO.inspect connect_info
    :error
  end

Apollo Client

Reconnecting the websocket link:

https://github.com/absinthe-graphql/absinthe/blob/master/guides/client/apollo.md

GraphiQL

Copy/paste token value (WS URL):

ws://localhost:4000/socket/?token=SFMyNTY.g3QAAAACZAAEZGF0YXQAAAABZAACaWRhAWQABnNpZ25lZG4GAMgb-zdrAQ.wZWad4dZpjtXRXSYEgenueik5_4rgfDD2trA7d7ru-k

2 Likes

This was helpful, I was using the wss protocol and banging my head against the wall for too long, thanks!