views:

217

answers:

2

I'm writing an application in Android that consumes some REST services I've created. These web services aren't issuing a standard Apache Basic challenge / response. Instead in the server-side code I'm wanting to interrogate the username and password from the HTTP(S) request and compare it against a database user to make sure they can run that service.

I'm using HttpClient to do this and I have the credentials stored on the client after the initial login (at least that's how I see this working). So here is where I'm stuck. Preemptive authenticate under HttpClient requires you to setup an interceptor as a static member. This is the example Apache Components uses.

    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        @Override
        public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                    ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };

So the question would be this. What would the proper use of this be? Would I spin this up as part of the application when the application starts? Pulling the username and password out of memory and then using them to create this CredentialsProvider which is then utilized by the HttpRequestInterceptor? Or is there a way to do this more dynamically?

+1  A: 

HttpClient does not like pre-emptive authentication very much.

If your REST API supports BASIC authentication, then it is probably simpler to just put in the proper header yourself. Here is a sample Twitter client, using the Twitter API, that uses this technique.

CommonsWare
I got it to work without preemptive authentication. That turned out to be the answer. Thanks.
Preston Crawford
A: 

Nevermind, I found out what was wrong. I took another look at the Apache examples and realized that I wasn't passing along the "http" when creating the HttpHost object I was using. It was completely unrelated. Ugh.

Preston Crawford