'GraphQL Apollo iOS Client Response Headers
I am using Apollo iOS client for doing GraphQL queries. I need to pass Auth token in the header which I am able to achieve using below code -
let apolloAuth: ApolloClient = {
let configuration = URLSessionConfiguration.default
let token = "Bearer \(UserDefaults.standard.string(forKey: "UserToken") ?? "")"
// Add additional headers as needed
configuration.httpAdditionalHeaders = ["Authorization": token]
let url = URL(string: "...URL.../graphql")!
return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))
}()
My fetch query goes as below -
apolloAuth.fetch(query: referralQuery){ (result, error) in
if let error = error {
print(error.localizedDescription)
return
}else{
self.referralId = result?.data?.referrals?.id
}
}
Now my Server returns a refreshed auth token after every request which is a part of response header. I need to get the token from the response header but I am unable to find out a way to do that. Can someone guide me on this.
Solution 1:[1]
The URLSessionConfiguration object comes with a shared HTTPCookieStorage singleton object. Once you set the apollo client with that configuration, what you could do is store the auth token in a cookie using your server, then send the cookies to the client on every request. Automatically, you will be able to access that cookie like so:
apollo.fetch(query: GraphQLQuery()) { result, error in
if let error = error { fatalError(error.localizedDescription) }
if let data = result?.data {
// do something with data
}
self.getCookies()
}
func getCookies() {
let cookies = HTTPCookieStorage.shared.cookies
if let c = cookies {
print(c)
// if your server sent a token inside a cookie, you will see it here
}
}
Solution 2:[2]
Use interceptors for reading the tokens from the response header.
Sample code:
class UserManagementInterceptor: ApolloInterceptor {
/// Helper function to add the token then move on to the next step
private func addTokenAndProceed<Operation: GraphQLOperation>(
to request: HTTPRequest<Operation>,
chain: RequestChain,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
if let headerFields = response?.httpResponse.allHeaderFields {
// Read the required tokens
}
chain.proceedAsync(request: request,
response: response,
completion: completion)
}
func interceptAsync<Operation: GraphQLOperation>(
chain: RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
addTokenAndProceed(to: request,
chain: chain,
response: response,
completion: completion)
}
}
Reference: Creating a client
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Huy-Anh Hoang |
| Solution 2 | Dileep |
