auth on a per topic basis #397
-
I currently authenticate the client in the
Once the user is connected, they can subscribe to specific chats within our app that they may or may not have access to. We currently check if a user should receive a message as we iterate through the active subscriptions in the subscribe function of the subscription resolver.
I would like to instead move the authentication logic to onSubscribe function so that only users with access can subscribe and we only have to check their access once when they subscribe to a topic. I worry that once we deny a connection, I'm not sure how to make the apollo hook useSubscription try to reconnect once they have gained access one way or another. I'd like to pose the question to the community and contributors: How would you recommend implementing authentication per user per chat? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You can indeed use the async function onSubscribe(ctx, msg) {
const can = await checkCanSubscribe(ctx, msg);
if (!can) {
// user doesnt have access, return error for this exact subscription
return [new GraphQLError('Forbidden')];
}
// user has access, return nothing to proceed with the regular flow
} |
Beta Was this translation helpful? Give feedback.
You can indeed use the
onSubscribe
server hook. To deny a subscription, you can just return an error from it and handle the error however you please on the client.