2009-07-22 88 views
5

我需要使用java来传递一个域用户帐户的凭证来使用其他Web服务。使用java UrlConnection进行ntlm(或kerberos)验证

现在我用传统的ASP


set xmlHttp = server.createObject("msxml2.serverxmlhttp") 
xmlHttp.open method, url, false, domain & "\" & user, password 
xmlHttp.send body 
out = xmlHttp.responseText 
set xmlHttp = nothing 

,并用asp.net



HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 

request.Credentials = new NetworkCredential(user, password, domain); 

request.Method = WebRequestMethods.Http.Get 

HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 

StreamReader outStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8) ; 

output = outStream.ReadToEnd(); 

做,我该怎么用java实现这一目标?考虑到我没有使用当前登录用户的凭据,我正在指定域帐户(我有密码)

请告诉我,它与使用经典的asp和asp.net一样简单.. ..

回答

0

根据this page,你可以使用使用内置的JRE类,但要注意早期版本的Java只能在Windows机器上执行此操作。

但是,如果您愿意接受第三方依赖关系,那么IMO Apache Commons HttpClient 3.x即可。 Here是使用身份验证(包括NTLM)的文档。一般来说,HttpClient是一个功能更强大的库。

最新版本的HttpClient是4.0,但是显然这个版本does not support NTLM这个版本requires a tiny bit of extra work

这是我认为代码会是什么样子,虽然我还没有尝试过:

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()); 

好运。

+0

嘿马特,非常感谢您的回答,但我不知道是否有可能做到这一点,与BUIL,在JRE类,使用Kerberos而不是NTLM .. 。我的意思是,Kerberos不是像NTLM那样的普遍的东西... – opensas 2009-07-26 18:54:24

+0

最后我听说,Apache客户端不支持NTLMv2。他们不愿意挖掘JCIFS,因为a)他们声称LGPLv2与他们的许可证不兼容; b)他们通常对MS的东西感到厌倦。但这并不重要,因为如果您想与Microsoft进行互操作,NTLM是认证机制的共同特征。如果客户端无法访问域控制器,或者时间同步关闭或者DNS不太正确或者等等,Kerberos不起作用。等等。 – user8134 2010-02-09 01:41:17

-2

查看SPNEGO HTTP Servlet Filter项目中的SpnegoHttpURLConnection类。这个项目也有一些例子。

该项目有一个client library几乎没有你在你的例子中做什么。

从的Javadoc看看这个例子...

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

    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()); 
} 
0

的java.net.URLStreamHandler中的java.net.URL和一个兼容的解决方案是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(); 

您也可以在url.openConnection(proxy)中使用java.net.Proxy。

使用Maven的相关性:

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