nKognito
nKognito

Reputation: 6363

Enable authenticator manually

Currently my client authenticates request only on case of 401 response:

this.client.authenticator(new okhttp3.Authenticator() {

      public Request authenticate(Route route, Response response) throws IOException {
      String credentials = authenticator.getCredentials();
      if (credentials.equals(response.request().header("Authorization"))) {
            throw new TraversonException(401, "Unauthorized", response.request().url().toString());
      } else {
            defaultHeader("Authorization", credentials);

            Request.Builder newRequest = response.request().newBuilder()
                                .headers(Headers.of(defaultHeaders));

             return newRequest.build();
         }
});

But I'd like to change this behavior and be able to call it either manually or auto per first call? Is it possible somehow?

Upvotes: 3

Views: 585

Answers (1)

Yuri Schimke
Yuri Schimke

Reputation: 13498

If the authentication is predictably required and not related to a proxy, then the solution is to implement an Interceptor instead of Authenticator.

OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();

Example Interceptor https://github.com/yschimke/oksocial/blob/48e0ca53b85e608443eab614829cb0361c79aa47/src/main/java/com/baulsupp/oksocial/uber/UberAuthInterceptor.java

n.b. There is discussion around possible support for this usecase in https://github.com/square/okhttp/pull/2458. One issue with current Authenticator API is that it assumes a Response from the failed (401) request.

Upvotes: 3

Related Questions