All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin-client.libraries.jvm-retrofit2.auth.HttpBearerAuth.kt.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
package {{packageName}}.auth

import java.io.IOException

import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response

{{^nonPublicApi}}{{#explicitApi}}public {{/explicitApi}}{{/nonPublicApi}}class HttpBearerAuth(
    private var schema: String = "",
    var bearerToken: String = ""
) : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Chain): Response {
        var request = chain.request()

        // If the request already have an authorization (eg. Basic auth), do nothing
        if (request.header("Authorization") == null && bearerToken.isNotBlank()) {
            request = request.newBuilder()
                .addHeader("Authorization", headerValue())
                .build()
        }
        return chain.proceed(request)
    }

    private fun headerValue(): String {
        return if (schema.isNotBlank()) {
            "${upperCaseBearer()} $bearerToken"
        } else {
            bearerToken
        }
    }

    private fun upperCaseBearer(): String {
        return if (schema.lowercase().equals("bearer")) "Bearer" else schema
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy