1

I've got a React app I'm trying work on struggling a little with implementing subscriptions with Hasura. My queries are working as they should but I'm getting the following error when trying to execute a subscription:

"cannot start as connection_init failed with : Miss…g Authorization header in JWT authentication mode"

When I log the token to my console it appears as it should. I've tried not splitting my links but get the same outcome.

  /* Graphql Start */
  const {
    isLoading,
    error,
    getAccessTokenSilently
  } = useAuth0();

  /* HTTP Link Start */
  const authLink = setContext(async () => {
    const token = await getAccessTokenSilently();
    return {
      headers: {
        Authorization: `Bearer ${token}`
      }
    };
  });

  const httpLink = createHttpLink({
    uri: 'https://####.hasura.app/v1/graphql', 
  });

  const newHttpLink = authLink.concat(httpLink);
  /* HTTP Link End */

  /* Websocket Start */
  const wsAuthLink = setContext(async () => {
    const token = await getAccessTokenSilently();
    return {
      options: {
        reconnect: true,
        timeout: 30000,
        connectionParams: {
          headers: {
            Authorization: `Bearer ${token}`
          } 
        }
      }
    };
  });

  const wsLink = new WebSocketLink({
    uri: 'wss://####.hasura.app/v1/graphql',
  });

  const newWSLink = wsAuthLink.concat(wsLink);
  /* Websocket End */

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      );
    },
    newWSLink,
    newHttpLink,
  );

  const client = new ApolloClient({
    link: splitLink,
    cache: new InMemoryCache(),
    connectToDevTools: true
  });
  /* Graphql End */
Blake Hayes
  • 53
  • 1
  • 5

1 Answers1

-1

in your wsLink make these fix:

const wsLink = new WebSocketLink({
  uri: "wss://####",
  options: {
    connectionParams: {
      headers: {
        Authorization: `Bearer ${token}`,
        "content-type": "application/json",
        "x-hasura-admin-secret": ####,
        "x-hasura-role": "###",
      },
    },
    reconnect: true,
  },
});
Pablo Fernandez
  • 143
  • 3
  • 9
  • 2
    Sorry if I'm misinterpreting but wouldn't this be a security vulnerability? You're circumventing user authentication by simply passing in `x-hasura-admin-secret`, which gives the client admin privileges. – vxm5091 Oct 11 '22 at 15:44