apollographql / apollo-ios

📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.
https://www.apollographql.com/docs/ios/
MIT License
3.89k stars 728 forks source link

How to pass http headers when making graphql subscription from ios #3436

Closed jisaacks closed 2 months ago

jisaacks commented 2 months ago

Question

I am using istio to intercept requests, authenticate an Access-Token header and then provide a X-User-ID header if the request was authenticated. (Otherwise the request gets stopped at the istio layer and never reaches the main server)

The server itself is an apollo graphql server that provides subscriptions.

When making a subscription to this server from a website, we just pass the Access-Token as a header, istio intercepts, injects the X-User-ID and everything is fine.

When it comes to ios, I cannot figure out how to pass header, the docs say to use connectingPayload like so:

let webSocketTransport: WebSocketTransport = {
  let url = URL(string: "ws://localhost:8080/websocket")!
  let webSocketClient = WebSocket(url: url, protocol: .graphql_transport_ws)
  let authPayload: JSONEncodableDictionary = ["authToken": myAuthToken]
  let config = WebSocketTransport.Configuration(connectingPayload: authPayload)
  return WebSocketTransport(websocket: webSocketClient, config: config)
}()

This does not seem to work when there is an istio layer. I think I need to just set headers for the request directly, but I cannot find docs that specify how.

andr3a88 commented 2 months ago

Try setting the header like this: webSocketClient.request.setValue(accessToken, forHTTPHeaderField: "Authorization")

I suggest using Postman to quickly test the connection to the websocket so you can figure out where to place the authentication token and see if it works!

calvincestari commented 2 months ago

Hi @jisaacks - there isn't another way unfortunately. The docs say to use connectingPayload because that's the supported way to supply auth for websockets. @andr3a88 is correct that you can probably set the headers directly on the request because the property is publicly exposed but it's not the supported method.

github-actions[bot] commented 2 months ago

Do you have any feedback for the maintainers? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo iOS usage and allow us to serve you better.