5. Authenticate your operations
3m

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 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 .

In Apollo.kt, add the AuthorizationInterceptor class:

app/src/main/kotlin/com/example/rocketreserver/Apollo.kt
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:

app/src/main/kotlin/com/example/rocketreserver/Apollo.kt
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 on the home screen. You should be able to inspect the request and see the headers with an Autorization key/value pair.

An open debugger showing the location of the breakpoint and the expected debugger output

After you've verified that the interceptor works as expected, remove the breakpoint.

Task!

Up next

Now that our are being authenticated, it's time to define additional to book and cancel trips.

Previous

Share your questions and comments about this lesson

This course is currently in

beta
. Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.