Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: HttpsUrlConnection with Authenticator for Basic Authentication iterates forever when password is wrong (on 401 response)

I am using an HttpsUrlConnection with Basic Authentication by using an Authenticator and setting a default Authenticator object like this:

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "userpass"
            .toCharArray());
    }
});

When I access my web-service the connection calls my getPasswordAuthentication() method to get the credentials and sends this to the web-server. This works allright as long as the password is correct. :)

However, it just happened that someone changed the basic authentication password on the web-server and then my request did not return.

I debugged it and what happens is that my call to getInputStream() never returns. The HttpsUrlConnection does get a 401 response and reacts to this internally by getting the same credentials again. But since I only provided one user and password this will fail again (and again...).

So my question is: How can I prevent this and where is there a hook to react to a wrong password (resp. a 401 response) so I can show an appropriate error message and cancel the request?

Here is an extract of the stack trace of the methods that are called repeatingly on HttpsUrlConnection:

1: MyOwnHttpConnection$3.getPasswordAuthentication() line: 99   
2: Authenticator.requestPasswordAuthentication(InetAddress, int, String, String, String) line: 162  
3: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).getAuthorizationCredentials(String) line: 1205 
4: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).processAuthHeader(String, String) line: 1178   
5: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).processResponseHeaders() line: 1118    
6: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).retrieveResponse() line: 1044  
7: HttpsURLConnectionImpl$HttpsEngine(HttpURLConnectionImpl).getInputStream() line: 523 
8: HttpsURLConnectionImpl.getInputStream() line: 283    
like image 738
Jens Avatar asked Oct 18 '11 13:10

Jens


2 Answers

I solved this problem by abstracting request/response logic away into a MyRequest class. This allows me to have a request-scoped variable that can tell my Authenticator whether it should make a request using a specified username and password, or whether it should stop retrying (by returning null). It looks somewhat like the following (consider this pseudocode)

public class MyRequest
{
    private boolean alreadyTriedAuthenticating = false;
    private URL url;

    ...

    public void send()
    {
        HttpUrlConnection connection = (HttpUrlConnection) url.openConnection();
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                if (!alreadyTriedAuthenticating)
                {
                    alreadyTriedAuthenticating = true;
                    return new PasswordAuthentication(username, password.toCharArray());
                }
                else
                {
                    return null;
                }
            }
            InputStream in = new BufferedInputStream(connection.getInputStream());

            ...

    }
}
like image 142
jsadler Avatar answered Sep 21 '22 20:09

jsadler


I wish I knew the proper answer to this, because I ran into the exact same problem. I couldn't find a way to handle the authentication error, or even get notified about it.

I ended up having to use HttpClient instead.

HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(loginUrl);
String authString = (userName+":"+password);
get.addHeader("Authorization", "Basic " + 
    Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
HttpResponse response = client.execute(get);

BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
like image 20
nynexman4464 Avatar answered Sep 20 '22 20:09

nynexman4464