As far as I can tell, JWT authentication does not work with websocket subscriptions on the web.
In my app, normal http graphql with JWT works fine, but subscription connections fail with the message
cannot start as connection_init failed with : Missing Authorization header in JWT authentication mode
From my naive reading of the code, and looking at #503, hasura looks for the Authorization header to be set, as with a "normal" request. Unfortunately, as far as my digging has taken me, the JS WebSocket API does not permit setting any headers (https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api, https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket)
The way Apollo works (and https://github.com/apollographql/subscriptions-transport-ws) is to send the headers (connection params) in init, but the JWT auth in hasura doesn't look there for the token based on my very limited understanding of the hasura internals.
@mwaldstein We really need to document this better.
Apollo client works perfectly with Hasura, if you set your headers as apollo intends them to be passed for subscriptions:
Create a wsLink:
const wsLink = new WebSocketLink(
new SubscriptionClient(WS_URL, {
reconnect: true,
timeout: 30000,
connectionParams: {
headers: {
Authorization: "Bearer xxxxx"
}
}
})
);
Now use wsLink with apollo client: https://blog.hasura.io/moving-from-apollo-boost-to-graphql-subscriptions-with-apollo-client-cc0373e0adb0
Please do let me know if you get stuck anywhere! @rikinsk Let's add this to the docs asap.
Ah! The nesting of headers under connectionParams... I see!
I was led astray by https://github.com/Akryum/vue-cli-plugin-apollo/blob/master/graphql-client/src/index.js#L104 which doesn't nest the headers in connectionParams...
Initial test suggests this fixed it - thanks! (sidebar - the discord invite appears broken...)
@mwaldstein thanks for letting us know about the Discord invite. Could you tell me where you found the link?
Fully tested our subscriptions and can now confirm they are all working - thanks from the assistance!
The Discord link is in the Readme - https://github.com/hasura/graphql-engine/blob/master/README.md#support--troubleshooting
Also document usage with webhook authentication (from #824)
related: #353 #472 #412
Tracked here #412
Most helpful comment
@mwaldstein We really need to document this better.
Apollo client works perfectly with Hasura, if you set your headers as apollo intends them to be passed for subscriptions:
Create a
wsLink:Now use
wsLinkwith apollo client: https://blog.hasura.io/moving-from-apollo-boost-to-graphql-subscriptions-with-apollo-client-cc0373e0adb0Please do let me know if you get stuck anywhere! @rikinsk Let's add this to the docs asap.