Implementing JWT authentication with subscriptions
This section explains how to implement authentication over WebSocket. Refer to the documentation at https://www.apollographql.com/docs/apollo-server/data/subscriptions/#operation-context for more information.
Until now, our subscriptions have not been secure, so we need to prevent subscriptions from users that are not authenticated. This means that we only allow WebSocket connections if the user is authenticated.
We can secure our subscriptions in the same way we did with queries and mutations. We simply need to pass a context parameter to our subscriptions each time a user connects over WebSocket!
When we create an instance of SubscriptionServer
, we can use an onConnect
function that gets executed before every WebSocket connection. This function accepts an object of the ConnectionParams
type as one of its arguments. If it returns an object, it gets passed to the resolvers as context.
Using ConnectionParams
, we can get...