Search code examples
javantlm

I want to login to a web page by passing credentials from java application


I want to login to a web page by passing credentials from java application? I am using below code but getting some error:

HttpClient client = new HttpClient();
client.getParams().setParameter("User Name", "user");
client.getParams().setParameter("Password", "password");
GetMethod request = new GetMethod("url");

error: INFO: No credentials available for NTLM @192.168.224.142:7048

I have also tried the below code:

HttpClient client = new HttpClient();
        client.getState().setCredentials(AuthScope.ANY, new NTCredentials("user", "password", "ip:port", "http"));
        GetMethod request = new GetMethod("url");

error:INFO: Failure authenticating with NTLM

suggest a way to login to a web page by passing credentials from java application?.


Solution

  • You are passing your user credentials as GET request parameters. The website expects an NTLM-based authentication (the username and password will not be sent to the server).

    Use org.apache.http.auth.NTCredentials to store your username and password.

    NTCredentials userCredentials = new NTCredentials(userName, password,
                                      System.getProperty("COMPUTERNAME"), domain);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
                                           AuthScope.ANY_PORT), userCredentials);
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setCredentialsProvider(credentialsProvider);
    HttpClient httpClient = HttpClientBuilder.create().
                          setDefaultCredentialsProvider(credentialsProvider).build();
    

    Feel free to modify the AuthScope to your needs.