Sling Academy
Home/Kotlin/Kotlin: Handling Authentication in API Calls (Basic, Bearer, OAuth)

Kotlin: Handling Authentication in API Calls (Basic, Bearer, OAuth)

Last updated: December 05, 2024

In modern application development, securing data and ensuring secure access to APIs is crucial. Kotlin, being a versatile language, provides robust libraries and features to handle authentication in API calls. In this article, we'll explore how to manage different types of authentications: Basic Authentication, Bearer Token, and OAuth, using Kotlin.

Basic Authentication

Basic Authentication is a simple authentication scheme built into the HTTP protocol. It requires the client sends the username and a password encoded in Base64 format as part of the request.

Before implementing Basic Authentication, you need to convert your credentials (username and password) into a Base64 string. Here’s how you can do this in Kotlin:


import java.util.Base64

fun basicAuthHeader(username: String, password: String): String {
    val credentials = "$username:$password"
    val base64Credentials = Base64.getEncoder().encodeToString(credentials.toByteArray())
    return "Basic $base64Credentials"
}

Once you have the header prepared, you can integrate it into your API call using a library like OkHttp.


import okhttp3.OkHttpClient
import okhttp3.Request

fun callApiWithBasicAuth(url: String, username: String, password: String) {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url(url)
        .header("Authorization", basicAuthHeader(username, password))
        .build()

    val response = client.newCall(request).execute()
    println(response.body()?.string())
}

Bearer Token Authentication

Bearer tokens are typically used to access resources in OAuth systems. The API call includes the token in the Authorization header as a bearer token.

Getting the bearer token often involves an authentication process where a POST request is made to an identity provider, providing client credentials. Assuming you already have a bearer token, here’s how you use it:


fun callApiWithBearerToken(url: String, bearerToken: String) {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url(url)
        .header("Authorization", "Bearer $bearerToken")
        .build()

    val response = client.newCall(request).execute()
    println(response.body()?.string())
}

OAuth Authentication

OAuth is an open-standard authorization protocol or framework that provides applications the ability to "secure designated access." OAuth doesn't share password data but instead uses authorization tokens to verify an identity.

Implementing OAuth in Kotlin typically involves using a library such as "kotlin-oauth" or using third-party authentication services like Google or OAuth.io. Here is an example of setting up an API call using OAuth:


import com.github.scribejava.core.builder.ServiceBuilder
import com.github.scribejava.core.oauth.OAuthService

val service: OAuthService = ServiceBuilder("")
    .apiSecret("")
    .callback("")
    .build()

// Exchange your verifier for access token
val tokenResponse = service.accessTokenRequest().execute()
val accessToken = tokenResponse.accessToken

fun callApiWithOauthToken(url: String, accessToken: String) {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url(url)
        .header("Authorization", "Bearer $accessToken")
        .build()

    val response = client.newCall(request).execute()
    println(response.body()?.string())
}

Implementing the various forms of authentication — Basic, Bearer, and OAuth — depends on the specific needs of your application, and understanding each method will help build more secure APIs. Remember to handle sensitive information like passwords and tokens carefully, implementing token expiration, and utilizing secure communication channels.

Next Article: Retrying Failed API Requests in Kotlin

Previous Article: How to Map API Responses to Kotlin Data Classes

Series: Networking in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin