Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp add Basic Authentication Header

Tags:

android

okhttp

I want to add Basic Authentication header to my request done with OkHttp3.

Here is my code:

        // Adding Authentication Header
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        });

        // 
        client.connectTimeout(10, TimeUnit.SECONDS);
        client.writeTimeout(10, TimeUnit.SECONDS);
        client.readTimeout(10, TimeUnit.MINUTES);

        RequestBody body = RequestBody.create(null, new byte[]{});
        if( json != null) {
            body = RequestBody.create(MediaType.parse(
                    "application/json"),
                    json.toString()
            );
        }

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.build().newCall(request).enqueue(callback);

Unfortunately no Authentication header is added and I really can't find the mistake.

like image 208
Gerke Avatar asked Jul 17 '26 19:07

Gerke


2 Answers

Authenticator is primarily intended for "reactive" authentication, i.e. it is not called automatically and every time. The main scenario for its automatic invocation is a 401 "Unauthorized" server response.

You should probably use a regular Interceptor instead for your case, just register it using your client builder like this:

client.addInterceptor(
   object : Interceptor { chain ->
       val request = chain.request().newBuilder()
            .addHeader(...)
            .build()
       return chain.proceed(request)
   }
)
like image 194
fraggjkee Avatar answered Jul 19 '26 07:07

fraggjkee


In order to do that, you need to use Interceptors offered by OkHttp Builder. Interceptors, as the name suggests, can intercept and requests sent through the client or any response received by the client before it passes them to your application.

In your case, you need to add this custom interceptor by intercepting the request, and attaching a new header to it before it leaves your client.

Adding a custom header to every request

return OkHttpClient.Builder()
    .addInterceptor { chain ->
        var request = chain.request()
        var url = request.url()


        request = request.newBuilder()
            .removeHeader("needAuthToken")
            .addHeader("Content-Type", "application/json")
            // Feel free to add any other headers
            .url(url)
            .build()

        chain.proceed(request)
}

Feel free to wrap this in any control flow conditions in case attachment of these headers matter on a predicate.

like image 27
Karan Dhillon Avatar answered Jul 19 '26 09:07

Karan Dhillon