Docs
Launch GraphOS Studio

11. Authenticate your operations


In this section you will learn how to add your login authorization token to your .

Create the AuthorizationInterceptor

Before you can book a trip, you need to be able to pass your authentication token along to the example server. To do that, let's dig a little deeper into how iOS's ApolloClient works.

The ApolloClient uses something called a NetworkTransport under the hood. By default, the client creates a RequestChainNetworkTransport instance to handle talking over HTTP to your server.

A RequestChain runs your request through an array of ApolloInterceptor objects which can mutate the request and/or check the cache before it hits the network, and then do additional work after a response is received from the network.

The RequestChainNetworkTransport uses an object that conforms to the InterceptorProvider protocol in order to create that array of interceptors for each it executes. There are a couple of providers that are set up by default, which return a fairly standard array of interceptors.

The nice thing is that you can also add your own interceptors to the chain anywhere you need to perform custom actions. In this case, you want to have an interceptor that will add your token.

First, create the new interceptor. Go to File > New > File... and create a new Swift File. Name it AuthorizationInterceptor.swift, and make sure it's added to the RocketReserver target. Open that file, and add the following code:

AuthorizationInterceptor.swift
import Foundation
import Apollo
import ApolloAPI
class AuthorizationInterceptor: ApolloInterceptor {
public var id: String = UUID().uuidString
func interceptAsync<Operation>(
chain: RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void
) where Operation : GraphQLOperation {
// TODO
}
}

Next, import KeychainSwift at the top of the file so you can access the key you stored in the keychain in the last step of the tutorial:

AuthorizationInterceptor.swift
import KeychainSwift

Then, replace the TODO within the interceptAsync method with code to get the token from the keychain, and add it to your headers if it exists:

AuthorizationInterceptor.swift
let keychain = KeychainSwift()
if let token = keychain.get(LoginView.loginKeychainKey) {
request.addHeader(name: "Authorization", value: token)
}
chain.proceedAsync(
request: request,
response: response,
interceptor: self,
completion: completion)

An array of ApolloInterceptors which are handed off to each request to perform in order is set up by an object conforming to the InterceptorProvider protocol. There's a DefaultInterceptorProvider which has an array with most of the Interceptors you'd want to use.

You can also make your own object conforming to InterceptorProvider - or, in this case, since the interceptor only needs to be added to the beginning of the list to run before all the other interceptors, you can subclass the existing DefaultInterceptorProvider.

Go to File > New > File... and create a new Swift File. Name it NetworkInterceptorProvider.swift, and make sure it's added to the RocketReserver target. Add code which inserts your AuthorizationInterceptor before the other interceptors provided by the DefaultInterceptorProvider:

NetworkInterceptorProvider.swift
import Foundation
import Apollo
import ApolloAPI
class NetworkInterceptorProvider: DefaultInterceptorProvider {
override func interceptors<Operation>(for operation: Operation) -> [ApolloInterceptor] where Operation : GraphQLOperation {
var interceptors = super.interceptors(for: operation)
interceptors.insert(AuthorizationInterceptor(), at: 0)
return interceptors
}
}

Another way to do this would be to copy and paste the list interceptors provided by the DefaultInterceptorProvider (which are all public), and then place your interceptors in the points in the array where you want them. However, since in this case we can run this interceptor first, it's simpler to subclass.

Use the interceptor

Next, go back to your Network class. Replace the ApolloClient with an updated lazy var which creates the RequestChainNetworkTransport manually, using your custom interceptor provider:

Network.swift
class Network {
static let shared = Network()
private(set) lazy var apollo: ApolloClient = {
let client = URLSessionClient()
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let provider = NetworkInterceptorProvider(client: client, store: store)
let url = URL(string: "https://apollo-fullstack-tutorial.herokuapp.com/graphql")!
let transport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)
return ApolloClient(networkTransport: transport, store: store)
}()
}

Now, go back to AuthorizationInterceptor.swift. Click on the line numbers to add a breakpoint at the line where you're instantiating the Keychain:

AuthorizationInterceptor.swift
let keychain = KeychainSwift()

Build and run the application. Whenever a network request goes out, that breakpoint should now get hit. If you're logged in, your token will be sent to the server whenever you make a request!

Now that your operations are being authenticated, it's time to define additional mutations to be able to book and cancel trips.

Previous
10. Write your first mutation
Next
12. Define additional mutations
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company