Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Understanding the Importance of Authentication

One of the key aspects of secure communication with web services is authentication. Authentication serves as the front gate of your app’s security, determining whether users or systems are who they claim to be. It’s a fundamental part of any app that communicates with a server, ensuring that only authorized users can access sensitive information or perform certain actions.

Understanding Authentication in Retrofit

Authentication credentials are usually sent as HTTP headers. Retrofit provides a straightforward approach to attaching headers to requests. You have the following options:

Adding a Static Header

If you have a fixed token or are using an API key that doesn’t change, you can use the @Headers annotation directly on your method, like in the following example.

@Headers("Authorization: Bearer example_token")
@GET("user/profile")
suspend fun getUserProfile(): UserProfile 

Adding a Dynamic Header

Dynamic headers are useful when your token or credentials might change over time, such as a token that gets refreshed. Check out the following example:

@GET("user/profile")
suspend fun getUserProfile(@Header("Authorization") token: String): UserProfile 

Using Interceptors

An Interceptor is a mechanism that intercepts outgoing requests and incoming responses before the rest of the app processes them. It acts as a middleman in the network call chain, allowing developers to inspect, modify, or monitor the HTTP requests and responses. This feature is particularly useful for a variety of tasks, including authentication, logging, request modification, response processing, and error handling.

Types of Interceptors

You’ll find two main types of interceptors in OkHttp, as you can see in the image below:

Iprqafojieh Debfuqs Wikta Iflfuwawaax Emfabvaysopw Toqtahq Obloszipdazv AvJkyx deki Kopuindm Tofhegwun Zuquotmn Wozmejkif
Wtnej oq Ensihbizhupq

Using Authenticator

OkHttp can automatically retry requests that fail due to lack of authentication. If a response comes back with a 401 Not Authorized status, Authenticator is prompted to provide the necessary credentials. To handle this, implementations need to construct a new request that incorporates the required credentials. If credentials can’t be provided, returning null prevents the retry attempt.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo