Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to pass Authorization header to Absinthe/Phoenix framework? #50

Closed
ademola-raimi opened this issue Jul 21, 2020 · 2 comments

Comments

@ademola-raimi
Copy link

ademola-raimi commented Jul 21, 2020

Intended outcome:

I want to pass an authorization header headers: { authorization: Bearer token } } to my WS connection

I tried:

  const wsClient = new PhoenixSocket(
  AUTH_ABSINTHE_SOCKET_ENDPOINT,
  {
    reconnect: true,
    connectionParams: () => ({
      headers: {
        'authorization': `Bearer ${token}`,
      },
    }),
  },
);
const link = createAbsintheSocketLink(AbsintheSocket.create(wsClient));

I also tried:

const authLink = setContext((_, { headers }) => {
  // Get the authentication token from the cookie if it exists.
  

  // Add the new Authorization header.
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

const wsLink = createAbsintheSocketLink(
	AbsintheSocket.create(
		new PhoenixSocket(AUTH_ABSINTHE_SOCKET_ENDPOINT, {
			reconnect: true,
			timeout: 30000,
			params: { UA: navigator.userAgent },
		})
	)
);

const link = authLink.concat(wsLink);

This is similar to the issue here.

@vadimshvetsov
Copy link

It's impossible because websocket connections are stateless and have no headers.

You can pass your token in params on connect.

const phoenixSocket = new PhoenixSocket('ws://localhost:4000/socket', {
  params: () => {
    const token = localStorage.getItem('token') // Or where do you store it

    return token ? { token } : {}
  },
})

And then hold it inside connection context on a backend side while it is active

defmodule YourAppWeb.UserSocket do
  use Phoenix.Socket
  use Absinthe.Phoenix.Socket, schema: YourAppWeb.Schema

  def connect(params, socket, _connect_info) do
    current_user = current_user(params) # Here you get user from params.token

    socket =
      Absinthe.Phoenix.Socket.put_options(socket,
        context: %{
          current_user: current_user
        }
      )

    {:ok, socket}
  end

  defp current_user(%{token: token}) do
    # How do you get user
  end

  defp current_user(_params), do: nil

  def id(_socket), do: nil
end

@peaceful-james
Copy link

For posterity: this is also in the docs
https://hexdocs.pm/absinthe/subscriptions.html#setting-options

@tlvenn tlvenn closed this as completed Apr 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants