Overview
We're logged into our app, but we haven't put our authorization token to work yet!
In this brief lesson, we will:
- Implement an OkHttp Interceptor to add headers to our GraphQL requests
- Finalize the logic to include our authorization token with all requests
Add an Authorization header
In this section, you will book a flight 🚀! Booking a flight requires being authenticated to the server so the correct person is sent to space! Since Apollo Kotlin is using OkHttp
under the hood for HTTP networking, we'll make use of their Interceptor
feature to add a header to our requests. That header will be read by the server to authenticate our mutation.
In Apollo.kt
, add the AuthorizationInterceptor
class:
private class AuthorizationInterceptor() : Interceptor {override fun intercept(chain: Interceptor.Chain): Response {val request = chain.request().newBuilder().apply {TokenRepository.getToken()?.let { token ->addHeader("Authorization", token)}}.build()return chain.proceed(request)}}
This interceptor appends an "Authorization: $token"
HTTP header to requests if the token is not null.
Now, we'll create a custom OkHttpClient
with that interceptor and pass it to our apolloClient
instance:
val apolloClient = ApolloClient.Builder().serverUrl("https://apollo-fullstack-tutorial.herokuapp.com/graphql").okHttpClient(OkHttpClient.Builder().addInterceptor(AuthorizationInterceptor()).build()).build()
Test the interceptor
And that's it! Now we'll verify that the interceptor is doing what we think it should do. Add a breakpoint in Apollo.kt
within AuthorizationInterceptor
, on the return
statement. Debug your app and tap any launch on the home screen. You should be able to inspect the request
variable and see the headers
attribute with an Autorization
key/value pair.
After you've verified that the interceptor works as expected, remove the breakpoint.
Up next
Now that our operations are being authenticated, it's time to define additional mutations to book and cancel trips.
Share your questions and comments about this lesson
This course is currently in
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.