space-cloud
space-cloud copied to clipboard
Document how token can be inserted in request for Apollo js client
We need a token to authenticate SC requests. We should add documentation on how we can do that. We need docs for the following:
- Add token as a header for queries and mutations
- Add token as a connection parameter for subscriptions: (refer: https://github.com/apollographql/apollo-link/issues/197). However I'm concerned how this will work and the token isn't available during the start time.
For reference: In SC's native websocket API, we send the token as a part of every request. So we do not face the same problem.
Is there currently a clean solution on how to change the token during runtime? For example if the user logs out and logs in with another account, and I want to resubscribe with the new token.
I am actively looking for a solution. @Jayesh333 did you find something?
Yess! After searching a lot, I found this in the official docs of Apollo - https://www.apollographql.com/docs/react/networking/authentication/
Not tested this, but looks good to meπ @erodactyl @YourTechBud
I don't think this will work for the ws connection.
I just found a solution, https://github.com/apollographql/apollo-server/issues/1505#issuecomment-419126391
This worked fine for me. The only issue I encountered is that "payload" argument wasn't added in the typescript file, so I suppose it's private.
Hey @YourTechBud, the solution which @erodactyl seems to be the only proper solution as of now. I tried the subscription middleware as pointed in that solution like this:
const wsLink = new WebSocketLink({
uri: websocketUrl,
options: {
reconnect: true,
},
webSocketImpl: ws,
})
const subscriptionMiddleware = {
applyMiddleware: async (options, next) => {
options.authToken = await getLoginToken()
next()
},
}
// add the middleware to the web socket link via the Subscription Transport client
wsLink.subscriptionClient.use([subscriptionMiddleware])
After doing this, the apollo client sends authToken
in the payload
object in every subscription start
message. This solves all our problem. We just need to use the payload.authToken
in the start
message on the backend to authorize the subscription request.
Done documenting this. Will be published along with the release of v0.17.0
subscriptionClient
is a private method.
ERROR in src/plugins/apollo.ts:52:8
TS2341: Property 'subscriptionClient' is private and only accessible within class 'WebSocketLink'.
50 | }
51 | // add the middleware to the web socket link via the Subscription Transport client
> 52 | wsLink.subscriptionClient.use([subscriptionMiddleware])
| ^^^^^^^^^^^^^^^^^^
@abinhho can you see if this works: https://www.apollographql.com/docs/react/networking/authentication/