Last active
May 16, 2020 03:19
-
-
Save cowlicks/71e766164647f224bf15f086ea34fa52 to your computer and use it in GitHub Desktop.
Dynamic auth tokens for Websockets with Graphql Subscriptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const subscriptionMiddleware = { | |
applyMiddleware: function(options, next) { | |
// Get the current context | |
const context = options.getContext().graphqlContext; | |
// set it on the `options` which will be passed to the websocket with Apollo | |
// Server it becomes: `ApolloServer({contetx: ({payload}) => (returns options) | |
options.authorization = context.authorization; | |
next() | |
}, | |
}; | |
const server = new ApolloServer({ | |
context: ({connection, payload, req}) => { | |
// whatever you return here can be accessed from the middleware of the SubscriptionMiddleware with | |
// applyMiddleware: (options, next) => options.getContext() | |
return {authorization: payload.authorization}; | |
}, | |
}); | |
const link = new WebSocketLink({ | |
uri: WS_URL, | |
webSocketImpl: WebSocket, | |
options: { | |
reconnect: true, | |
} | |
}); | |
link.subscriptionClient.use([subscriptionMiddleware]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment