Question

I'm talking to a webservice in Android using basic auth. This means I am sending a header looking like

Authorization Basic [user:pass base 64 string here]

I'm setting up my request thus:

public CreateUserService(Intent intent, int id) throws UnsupportedEncodingException {
    super(id);
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("email", intent.getStringExtra(FeedIntentService.EXTRA_UID)));
    //and so on.

    setupRequest(null, params);
}

and then in a superclass I have a method

protected void setupRequest(List<Header> headers, List<NameValuePair> params) throws UnsupportedEncodingException {
    mRequest = new HttpPost(getUri());
    mRequest.addHeader(new BasicHeader("Authorization", "Basic " + AUTH_STRING));
    //AUTH_STRING = the base 64 encoded user:pass pair
    if(headers!=null) {
        for(Header h: headers) {
            mRequest.addHeader(h);
        }
    }
    if(params!=null)
        ((HttpEntityEnclosingRequestBase) mRequest).setEntity(new UrlEncodedFormEntity(params));
}

The trouble is the server isn't receiving my request body. I read the request in fiddler and indeed it seems to be missing. However, when I remove the line

    mRequest.addHeader(new BasicHeader("Authorization", "Basic " + AUTH_STRING);

and look at the request in fiddler, I can see the body just as I would have expected, though obviously the server rejects the unauthorized request.

The AUTH_STRING is being encoded like this:

private static final String APP_KEY = "user";
private static final String APP_SECRET = "pass";
private static final String APP_STRING = APP_KEY + ":" + APP_SECRET;
private static final String APP_BASE_64 = Base64.encodeToString( APP_STRING.getBytes() , Base64.DEFAULT );
Was it helpful?

Solution

Just following up on my comment that lead to your solution.

In most cases, I find that when the base64-encoded String in the Auth header is invalid, servers tend to behave strangely. So verify that the Authorization Header is correct.

In general, it's always best to try these kinds of things with curl first. The following is an example command with curl

curl -X POST -H "Authorization: Basic <base64-encoded String>" http://some.server.url.com/some-endpoint

I see you added trim() to fix it. The real solution is to use Base64.NO_WRAP (http://developer.android.com/reference/android/util/Base64.html#NO_WRAP). So you want to do this when encoding:

Base64.encodeToString( APP_STRING.getBytes() , Base64.NO_WRAP );

I should have probably noticed that the first time around but either way, I'm glad my first thought lead to your answer :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top