authenticate with ntlm (or kerberos) using java UrlConnection

纵然是瞬间 提交于 2019-12-04 07:23:05

According to this page, you can use the built-in JRE classes, with the caveat that earlier versions of Java can only do this on a Windows machine.

However, if you are willing to live with a 3rd-party dependency, IMO Apache Commons HttpClient 3.x is the way to go. Here is the documentation for using authentication, including NTLM. In general, HttpClient is a much more functional library.

The latest version of HttpClient is 4.0, but apparently this version does not support NTLM this version requires a tiny bit of extra work.

Here is what I think the code would look like, although I haven't tried it:

HttpClient httpClient = new HttpClient();
httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(user, password, hostPortionOfURL, domain));
GetMethod request = new GetMethod(url);
BufferedReader reader = new InputStreamReader(request.getResponseBodyAsStream());

Good luck.

A compatible solution for java.net.URLStreamHandler and java.net.URL is com.intersult.net.http.NtlmHandler:

NtlmHandler handler = new NtlmHandler();
handler.setUsername("domain\\username");
handler.setPassword("password");
URL url = new URL(null, urlString, handler);
URLConnection connection = url.openConnection();

You also can use java.net.Proxy within url.openConnection(proxy).

Use Maven-Dependency:

    <dependency>
        <groupId>com.intersult</groupId>
        <artifactId>http</artifactId>
        <version>1.1</version>
    </dependency>

Take a look at the SpnegoHttpURLConnection class in the SPNEGO HTTP Servlet Filter project. This project has some examples as well.

This project has a client library that pretty much does what you are doing in your example.

Take a look this example from the javadoc...

 public static void main(final String[] args) throws Exception {
     final String creds = "dfelix:myp@s5";

     final String token = Base64.encode(creds.getBytes());

     URL url = new URL("http://medusa:8080/index.jsp");

     HttpURLConnection conn = (HttpURLConnection) url.openConnection();

     conn.setRequestProperty(Constants.AUTHZ_HEADER
             , Constants.BASIC_HEADER + " " + token);

     conn.connect();

     System.out.println("Response Code:" + conn.getResponseCode());
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!