Search code examples
androidhttpkotlinpostbasic-authentication

How to send a POST with basic auth using kotlin on an android app


Before anything, I'd like to mention that I'm fine using any library if it would help speed up or simplify the process.

I need to send a post request to an endpoint (http://myserver.com/api/data/save). The body must be a json with this structure:

{
   "id": "ABCDE1234",
   "date": "2021-05-05",
   "name": "Jason"
}

So, I need to make a post request. The endpoint requires authentication, so I need to incorporate the username and password. Where and how do I add them?

Best regards


Solution

  • Where and how do I add them?

    There are multiple ways to add your authentication details to any API request. Assuming you are using Retrofit 2, one of the ideal ways to implement this is using OkHttp Interceptors.

    You need a class implementing Interceptor

    class AuthInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
    
            // Add auth details here
            if (request.header("Authentication-required") != null) {
                request = request.newBuilder()
                    .addHeader("username", "username value")
                    .addHeader("password", "password value")
                    .build()
            }
    
            return chain.proceed(request)
        }
    }
    

    In your API interface add a header to the respective API which requires authentication

    @Headers("Authentication-required")
    @POST("/save")
    fun doSave(@Body data: PostData): Call<Status>
    

    Finally, build your retrofit client with OkHttpClient as

    val authClient = OkHttpClient.Builder()
        .addInterceptor(AuthInterceptor())
        .build()
    
    val retrofit = Retrofit.Builder()
        .baseUrl(your_base_url)
        .client(authClient)
        .build()