簡體   English   中英

使用 java UrlConnection 對 ntlm(或 kerberos)進行身份驗證

[英]authenticate with ntlm (or kerberos) using java UrlConnection

我需要使用 java 使用 rest web 服務,傳遞域用戶帳戶的憑據。

現在我正在使用經典的 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 一樣簡單....

根據此頁面,您可以使用內置的 JRE 類,但需要注意的是,早期版本的 Java 只能在 Windows 機器上執行此操作。

但是,如果您願意忍受第 3 方依賴項,IMO Apache Commons HttpClient 3.x是您的不二之選。 是使用身份驗證的文檔,包括 NTLM。 一般來說,HttpClient 是一個功能更強大的庫。

HttpClient 的最新版本是 4.0,但是顯然這個版本不支持 NTLM 這個版本需要一些額外的工作

這是我認為代碼的樣子,盡管我還沒有嘗試過:

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

祝你好運。

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>

查看 SPNEGO HTTP Servlet Filter 項目中的 SpnegoHttpURLConnection 類。 這個項目也有一些例子。

該項目有一個客戶端庫,它幾乎可以完成您在示例中所做的工作。

看看這個來自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());
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM