question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Provide default implementation for Basic / Bearer authentication

See original GitHub issue

Hi,

we all know that authentication can be handled using Authenticators and/or Interceptors. Would it be useful to provide default implementations for Basic auth and Bearer token auth. Guess this could be common tasks that are performed by many client applications.

Impl for interceptor could look like this, passing the credentials in the constructor … the authenticator could use something of a Callback interface so that the application can provide its credentials

wdyt?

import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

public class BasicAuthenticationInterceptor implements Interceptor {

    private final String userName;
    private final String password;

    public BasicAuthenticationInterceptor(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request request = chain.request()
                .newBuilder()
                .addHeader("Authorization", Credentials.basic(userName, password))
                .build();

        return chain.proceed(request);
    }

}
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.net.Proxy;
import java.net.URLEncoder;

/** Inspired by https://github.com/square/okhttp/wiki/Recipes */
public class BasicAuthenticationAuthenticator implements Authenticator {

    public interface Callback {

        String username();

        String password();
    }

    private final Callback callback;
    private final int maxRetries;

    public BasicAuthenticationAuthenticator(Callback callback) {
        this(callback, 3);
    }

    public BasicAuthenticationAuthenticator(Callback callback, int maxRetries) {
        this.callback = callback;
        this.maxRetries = maxRetries;
    }

    @Override
    public Request authenticate(Proxy proxy, Response response) throws IOException {
        if (responseCount(response) >= maxRetries) {
            return null; // If we've failed 3 times, give up.
        }

        final String username = URLEncoder.encode(callback.username());
        final String password = URLEncoder.encode(callback.password());
        final String credential = "Basic " + Credentials.basic(username, password);
        if (credential.equals(response.request().header("Authorization"))) {
            return null; // If we already failed with these credentials, don't retry.
        }

        return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
    }

    @Override
    public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
        return null;
    }

    private int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }

        return result;
    }

}

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:18 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
swankjessecommented, Apr 24, 2016

For basic auth you can just set the header manually. See the Credential class to build a basic auth header.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Bearer Authentication - Swagger
Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens.
Read more >
Simple OAuth: token bearer authentication for Drupal 8
Simple OAuth is an implementation of the OAuth 2.0 Authorization ... You can create your own token resources or use the default Global....
Read more >
JWT Bearer Authentication and Authorization for ASP.NET ...
An introduction on how to configure JWT Bearer authentication and authorization (based on scopes) for your ASP.NET Core 5 APIs.
Read more >
How to Set Up Java Spring Boot JWT Authorization and ...
We will start by creating controllers to save users securely and authenticate them based on username and password. We have a model entity...
Read more >
Authorizing requests - Postman Learning Center
By default Postman will append the access token to Bearer in the Authorization header for your request, but if your server implementation ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found