Skip to content

Authorization 🔐

The authorization flow is described here.

To authorize the user, the Yoli API expects an authorization header on almost every request. To realize this concept we used Interceptors from OkHttp

TokenInterceptor

The TokenInterceptor intercepts every request and adds the access token to the header. The TokenInterceptor inherits from OkHttp-Interceptor and gets added to the OkHttpClient. We create the TokenInterceptor in the RepositoryModule in our sample project.

A basic TokenInterceptor could look like this:

class TokenInterceptor(private val token: Token) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain
                .request()
                .newBuilder()
                .addHeader("authorization", token.accessToken)

        return chain.proceed(builder.build())
    }
}

TokenAuthenticator

If the access token in the authorization header is not valid, e.g. it expired, the Yoli API responds with a 301-HTTP-Error. By using an Authenticator from OkHttp we can automatically detect these 301-HTTP-Errors and respond to them.

A simple implementation could look like this:

class TokenAuthenticator(private val token: Token) : Authenticator {

    lateinit var repository: Repository?

    override fun authenticate(route: Route?, response: Response): Request? {

        // request a new access token
        repository?.getAccessTokenRx(token)

        return response
                .request()
                .newBuilder()
                .removeHeader("authorization")
                .addHeader("authorization", token.accessToken)
                .build()
    }
}