Android Networking: Beyond the Basics

Sep 8 2022 · Kotlin 1.7.10, Android 12, Android Studio Chipmunk

Part 1: Implement Advanced Retrofit

05. Intercept Authentication

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Challenge: Error Handling Next episode: 06. Challenge: Authentication & REST Methods

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Most server APIs require you to send an authorization token, whenever you’re trying to access an endpoint that requires a user id or email. This is why you’ve sent the user token as a header parameter in many requests. But it would be a cool thing if you could automatically send the token, once you’re logged in, right? Well, you can, using interceptors!

Demo

Open the RetrofitBuilders.kt file, and start by adding this constant, to represent the authorization header:

private const val HEADER_AUTHORIZATION = "Authorization"
.addInterceptor(buildAuthorizationInterceptor())
fun buildAuthorizationInterceptor() = object : Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val originalRequest = chain.request()

    if (App.getToken().isBlank()) return chain.proceed(originalRequest)

    val new = originalRequest.newBuilder()
        .addHeader(HEADER_AUTHORIZATION, App.getToken())
        .build()

    return chain.proceed(new)
  }
}
@GET("/api/note")
fun getNotes(): Call<GetTasksResponse>

@GET("/api/user/profile")
fun getMyProfile(): Call<UserProfileResponse>

@POST("/api/note/complete")
fun completeTask(@Query("id") noteId: String): Call<CompleteNoteResponse>

@POST("/api/note")
fun addTask(@Body request: AddTaskRequest): Call<Task>