Skip to content

Commit a43bd0e

Browse files
committed
feat: add authorization via connectionParams
1 parent 15090cb commit a43bd0e

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
@@ -265,3 +265,40 @@ GraphQLModule.forRoot({
265265
}
266266
}),
267267
```
268+
269+
#### Authorization over WebSocket
270+
271+
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/)).
272+
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)).
273+
274+
```typescript
275+
GraphQLModule.forRoot({
276+
installSubscriptionHandlers: true,
277+
subscriptions: {
278+
onConnect: (connectionParams) => {
279+
// extract the token
280+
const authToken = connectionParams.authToken;
281+
// validate the token (e.g., signature, expiration for jwt)
282+
if (!isValid(authToken)) {
283+
throw new Error('Token is not valid');
284+
}
285+
// extract user information from token
286+
const user = parseToken(authToken);
287+
// return user info to add them to the context later
288+
return { user };
289+
},
290+
},
291+
context: ({ connection }) => {
292+
// connection.context will be equal to what was returned by onConnect
293+
// now user info is available inside context.req.user
294+
return {
295+
req: connection?.context ?? {},
296+
};
297+
},
298+
}),
299+
```
300+
301+
The `authToken` in this example is only sent once by the client, when the connection is first established.
302+
All subscriptions made with this connection will have the same `authToken`, and thus the same user info.
303+
304+
> 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)