You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/graphql/subscriptions.md
+37Lines changed: 37 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -294,3 +294,40 @@ GraphQLModule.forRoot({
294
294
}
295
295
}),
296
296
```
297
+
298
+
#### Authorization over WebSocket
299
+
300
+
Checking that the user is authenticated should be done inside the `onConnect` property of the `subscriptions` options (read [more](https://www.apollographql.com/docs/graphql-subscriptions/authentication/)).
301
+
The `onConnect` will receive as first argument the `connectionParams` passed to the `SubscriptionClient` (read [more](https://www.apollographql.com/docs/react/data/subscriptions/#4-authenticate-over-websocket-optional)).
302
+
303
+
```typescript
304
+
GraphQLModule.forRoot({
305
+
installSubscriptionHandlers: true,
306
+
subscriptions: {
307
+
onConnect: (connectionParams) => {
308
+
// extract the token
309
+
const authToken =connectionParams.authToken;
310
+
// validate the token (e.g., signature, expiration for jwt)
311
+
if (!isValid(authToken)) {
312
+
thrownewError('Token is not valid');
313
+
}
314
+
// extract user information from token
315
+
const user =parseToken(authToken);
316
+
// return user info to add them to the context later
317
+
return { user };
318
+
},
319
+
},
320
+
context: ({ connection }) => {
321
+
// connection.context will be equal to what was returned by onConnect
322
+
// now user info is available inside context.req.user
323
+
return {
324
+
req: connection?.context?? {},
325
+
};
326
+
},
327
+
}),
328
+
```
329
+
330
+
The `authToken` in this example is only sent once by the client, when the connection is first established.
331
+
All subscriptions made with this connection will have the same `authToken`, and thus the same user info.
332
+
333
+
> warning **Note** There is a bug in `subscriptions-transport-ws` that allows connections to skip the `onConnect` phase (read [more](https://github.com/apollographql/subscriptions-transport-ws/issues/349)). You should not assume that `onConnect` was called when the user starts a subscription, and always check that the `context` is populated.
0 commit comments