Search code examples
javaiishttprequestntlm-authentication

HTTP request gets authorized and unauthorized on different environments with as it seems same setup


We have a funny situation where basic GET HTTP request doesn't pass Windows NTLM autorization at IIS server. At the same time we have same code running on another environment which gets successfully executed.

When we repeat request via browser it gets successfully executed.

It seems that somehow Java code doesn't send correct authorization information with the request. We are trying to figure out how this can be. Classes used are from java.net package. We tried switching account to Local System under which Tomcat is running back and forth with no success.

Code is as simple as it can be:

public static String sendHttpRequest(String urlString, String method, boolean 
disconnect) {

    HttpURLConnection urlConnection = null;
    String result = null;
    try {

        URL url = new URL(urlString);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("Content-Length", "0");

        urlConnection.setRequestMethod(method);
        urlConnection.setUseCaches(false);

         StringBuilder sb = new StringBuilder();
        try (InputStream is = urlConnection.getInputStream()) {

             InputStream buffer = new BufferedInputStream(is);
            Reader reader = new InputStreamReader(buffer, "UTF-8");
            int c;

            while ((c = reader.read()) != -1) {
                sb.append((char) c);
            }
        }

        int statusCode = urlConnection.getResponseCode();
        if (statusCode < 200 || statusCode >= 300) {

        } else
            result = sb.toString();

    } catch (IOException e) {
        LOGGER.warning(e.getMessage());
    } finally {
        if (disconnect && urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    return result;
}

Explicit questions to answer: How to log/trace/debug information used for authentication purpose on the client side? Any hint would be appreciated :)


Solution

  • Apache HttpClient in it's newer versions supports native Windows Negotiate, Kerberos and NTLM via SSPI through JNA when running on Windows OS. So if you have the option to use the newer version (from 4.4 I believe), this is a non-issue.

    For example: http://hc.apache.org/httpcomponents-client-4.4.x/httpclient-win/examples/org/apache/http/examples/client/win/ClientWinAuth.java