Search code examples
androidapache-httpclient-4.xapache-commons-httpclient

Multi Auth methods Apache http client 4.3+


I have a few servers with different Auth types. Basic, NTLM. I need mechanism to select it automaticly. I see that as trying with each credential type, and select that was successful. I found some method in http client 4.3, named impl.client.HttpClientBuilder#setDefaultAuthSchemeRegistry, but

  1. I have no idea how to use that.
  2. Second question, how I can control priority of auth methods. Because I want to determine which method for the url I should use, and then want to start from successful method on last request.

PS as for now i have workable realization for each type of auth.


Solution

  • One can configure preferred auth schemes on a per request basis using RequestConfig

    RequestConfig requestConfig =  RequestConfig.custom()
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .build();
    

    Local execution context contains all the details pertaining to request execution including auth state for target and proxy hosts

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpClientContext localContext = HttpClientContext.create();
        HttpGet httpget = new HttpGet("http://localhost/");
        CloseableHttpResponse response = httpclient.execute(httpget, localContext);
        try {
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
            AuthState targetAuthState = localContext.getTargetAuthState();
            if (targetAuthState.getAuthScheme() != null) {
                System.out.println("Target auth scheme: " +
                        targetAuthState.getAuthScheme().getSchemeName());
            }
            AuthState proxyAuthState = localContext.getProxyAuthState();
            if (proxyAuthState.getAuthScheme() != null) {
                System.out.println("Proxy auth scheme: " +
                        proxyAuthState.getAuthScheme().getSchemeName());
            }
    
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }