Skip to content

Commit f8b89bf

Browse files
Merge branch 'gql-subscriptions-auth' of https://github.com/asmeikal/docs.nestjs.com into asmeikal-gql-subscriptions-auth
2 parents 0176e04 + a43bd0e commit f8b89bf

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

content/graphql/subscriptions.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,3 +294,40 @@ GraphQLModule.forRoot({
294294
}
295295
}),
296296
```
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+
throw new Error('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

Comments
 (0)