10

The problem here is consuming a web resource that has NTLM authentication while using the Apache HttpClient on the client side. The issue I am having is forcing the client to use NTLM authentication. here is a code sapmle.

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory());
NTCredentials creds = new NTCredentials("_myUSer_","_myPass_","_myWorkstation_","_myDomain_");
httpclient.getCredentialsProvider().setCredentials( new AuthScope("serverName",80), creds);
List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.NTLM);
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
HttpHost target = new HttpHost("serverName", 80, "http");
HttpGet httpget = new HttpGet("webResource");
HttpContext localContext = new BasicHttpContext();
HttpResponse response = httpclient.execute(target, httpget, localContext);

Here is the error from Java:

org.apache.http.client.protocol.RequestTargetAuthentication process
SEVERE: Authentication error: Invalid name provided (Mechanism level: Could not load configuration file C:\WINDOWS\krb5.ini (The system cannot find the file specified))

The web server response is a 401.

Any ideas on why the auth policy not being set correctly? Am I missing something in the code?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Kelly
  • 111
  • 1
  • 1
  • 5
  • 1
    I found one issue with my code and that is that the AuthScope should point to your proxy and not your target, that did get rid of the errors where it was trying to use Kerberos instead of NTLM, but I am still getting a 401 from the server, any ideas on the correct username/pass/domain combination? – Kelly Apr 21 '11 at 16:35
  • 1
    HttpClient need to be updated check my post [http://stackoverflow.com/questions/5917356/httpclient-4-1-1-returns-401-when-authenticating-with-ntlm-browsers-work-fine/20047880#20047880][1] [1]: http://stackoverflow.com/questions/5917356/httpclient-4-1-1-returns-401-when-authenticating-with-ntlm-browsers-work-fine/20047880#20047880 – Mohammed Irfan Tirupattur Nov 19 '13 at 11:43

4 Answers4

5

I have a similar situation and I suspect that you are setting the wrong parameter: AuthPNames.PROXY_AUTH_PREF. I use AuthPNames.TARGET_AUTH_PREF and all seems to work fine.

evandongen
  • 1,995
  • 17
  • 19
2

Here is my solution to this Problem: And "evandongen" is right.

Please note the use of the URIBuilder.

String username = "uid";
String pwd = "pwd";
String servername = "www.someserver.com";
String workstation = "myworkstation";
String domain = "somedomain";
String relativeurl = "/util/myservice.asmx";

String oldimagePath = "\\mypath\\image.jpg";

DefaultHttpClient httpclient = new DefaultHttpClient();

try {
    httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory());
    NTCredentials creds = new NTCredentials(username,pwd,workstation,domain);

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(servername,80), creds);

        List authpref = new ArrayList();

        authpref.add(AuthPolicy.NTLM);

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http")
            .setHost(servername)
            .setPath(relativeurl + "/DeleteImage")
            .setParameter("imagePath", oldimagePath);
        URI uri = builder.build();

        httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        HttpHost target = new HttpHost(servicename, 80, "http");
        HttpGet httpget = new HttpGet(uri);

        HttpContext localContext = new BasicHttpContext();

        HttpResponse response1 = httpclient.execute(target, httpget, localContext);

        BufferedReader reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent())); 

        String line = reader.readLine(); 
        while (line != null) 
        { 
            System.out.println(line);
            line = reader.readLine(); 
        } 

} catch (Exception e) {
    System.out.println("Exception:"+e.toString());
} finally {
    // End
}
0

HttpClient did not work for me but the below snippet did. Reference - http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html

    public static String getResponse(String url, String userName, String password) throws IOException {
    Authenticator.setDefault(new Authenticator() {
      @Override
      public PasswordAuthentication getPasswordAuthentication() {
        System.out.println(getRequestingScheme() + " authentication");
        return new PasswordAuthentication(userName, password.toCharArray());
      }
    });

    URL urlRequest = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");

    StringBuilder response = new StringBuilder();
    InputStream stream = conn.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
    String str = "";
    while ((str = in.readLine()) != null) {
      response.append(str);
    }
    in.close();

    return response.toString();
  }
Smitesh
  • 355
  • 1
  • 3
  • 6
0

I think this is because of a defect, see here.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260