-
Hi, thank you and the community making a great work on this package. I would like to ask in case of authentication or authorization changed, how do we unsubscribe or disconnect the socket from server side? StoryThe client connect to server, it will go through onConnect and server check for authentication in header, assume passed.
It will go through onSubscribe, here we check for authorization if that user can access that event from that orgId, assume passed. Acceptance criteria
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I always recommend to completely kick off the client for re-authentication. It will have the client re-run the connecting phase allowing the server to properly authorise. Once the client reconnects, it will resubscribe all previously active subscriptions. Assuming you're using the built-in servers, the socket is always available in the context's extras. I recommend closing with the import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { CloseCode } from 'graphql-ws';
const server = new WebSocketServer({
port: 4000,
path: '/graphql',
});
useServer(
{
// ...
onConnect: (ctx) => {
ctx.extra.socket.close(CloseCode.Forbidden);
},
onSubscribe: (ctx) => {
// or
ctx.extra.socket.close(CloseCode.Forbidden);
},
onNext: (ctx) => {
// or
ctx.extra.socket.close(CloseCode.Forbidden);
},
onError: (ctx) => {
// or
ctx.extra.socket.close(CloseCode.Forbidden);
},
onComplete: (ctx) => {
// or
ctx.extra.socket.close(CloseCode.Forbidden);
},
},
server,
);
I still recommend kicking off the client completely since it's much safer, but if you want this approach still - you'll have to build the logic yourself. You can find the list of all active subscriptions in |
Beta Was this translation helpful? Give feedback.
I always recommend to completely kick off the client for re-authentication. It will have the client re-run the connecting phase allowing the server to properly authorise. Once the client reconnects, it will resubscribe all previously active subscriptions.
Assuming you're using the built-in servers, the socket is always available in the context's extras. I recommend closing with the
4403: Forbidden
close code, but you're free to close with any non-fatal close code you wish. For example, withgraphql-ws/lib/use/ws
: