Skip to main content

Accessing Protected APIs

Cloud has the newest features. Some may not be in a release yet; the newest release is Identity & Access Management 7.3.0.

When your app needs to call a backend API that requires authentication, use ThunderIDClient.getAccessToken() to retrieve a valid access token and attach it as a Bearer token to your requests. The SDK automatically refreshes the token if it has expired.

Accessing Protected APIs​

1. Using HttpURLConnection​

The following example calls a protected API endpoint using the standard Android HttpURLConnection:

ApiClient.kt

suspend fun fetchProtectedResource(thunder: ThunderIDState): String {
val token = thunder.client.getAccessToken()

return withContext(Dispatchers.IO) {
val connection = URL("https://api.identity-platform.us.cloud.wso2.com/api/resource").openConnection() as HttpURLConnection
connection.setRequestProperty("Authorization", "Bearer $token")
connection.setRequestProperty("Accept", "application/json")

check(connection.responseCode in 200..299) {
"Request failed: ${connection.responseCode}"
}

connection.inputStream.bufferedReader().readText()
}
}

2. Token Refresh​

getAccessToken() refreshes the access token automatically when it is expired, as long as a valid refresh token is available. You do not need to handle refresh manually. If the refresh token is also expired, getAccessToken() throws IAMException with code SESSION_EXPIRED. Handle this by signing the user out:

try {
val token = thunder.client.getAccessToken()
// use token
} catch (e: IAMException) {
if (e.code == IAMErrorCode.SESSION_EXPIRED) {
runCatching { thunder.client.signOut() }
thunder.refresh()
} else {
println("Unexpected error: $e")
}
}

3. Using OkHttp​

If your project uses OkHttp, create an Interceptor that injects the access token:

ThunderIDInterceptor.kt

class ThunderIDInterceptor(private val thunder: ThunderIDState) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token = runBlocking { thunder.client.getAccessToken() }
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
return chain.proceed(request)
}
}

4. Using Retrofit​

If your project uses Retrofit, combine it with the OkHttp interceptor above:

val retrofit = Retrofit.Builder()
.baseUrl("https://api.identity-platform.us.cloud.wso2.com/")
.client(
OkHttpClient.Builder()
.addInterceptor(ThunderIDInterceptor(thunder))
.build()
)
.addConverterFactory(GsonConverterFactory.create())
.build()

val api = retrofit.create(MyApiService::class.java)

Was this page helpful?