最近一個項目拿到客戶那運行不了 。 原來我的 這個項目要和另一個系統通過http的接口進行通訊。但在客戶的生產環境中,那套系統將web應用的登錄和 Windows Domain的登錄結合,做了一個sso單點登錄(jcifs實現)。那么我必須要修改我的程序,好自動登錄 Windows Domain。
通過抓包分析,局域網使用的是NTLM 協議。
當通過瀏覽器訪問被 NTLM協議 保護的資源的時候, NTLM 的認證方式和流程如下:
1: C --> S GET ... 2: C <-- S 401 Unauthorized WWW-Authenticate: NTLM 3: C --> S GET ... Authorization: NTLM <base64-encoded type-1-message> 4: C <-- S 401 Unauthorized WWW-Authenticate: NTLM <base64-encoded type-2-message> 5: C --> S GET ... Authorization: NTLM <base64-encoded type-3-message> 6: C <-- S 200 Ok
Type-1 消息包括機器名、 Domain 等
Type-2 消息包括 server 發出的 NTLM challenge
Type-3 消息包括用戶名、機器名、 Domain 、以及兩個根據 server 發出的 challenge 計算出的 response ,這里 response 是基于 challenge 和當前用戶的登錄密碼計算而得
PS:在第二步時,當瀏覽器接收到一個401 Unauthorized 的 response ,會 彈出該對話框讓用戶輸入用戶名、密碼。(ie有可能會自動登錄)
我的程序(client)要和另個程序走http接口通訊(server), server再去ad驗證域登錄
httpclient 實現NTLM驗證(當然你也可以自己實現協議)
HttpClient從version 4.1
開始
完全支持
NTLM authentication protocol(NTLMv1, NTLMv2, and NTLM2 ),
文檔的原話是“The NTLM authentication scheme is significantly more expensive in terms of computational overhead
and performance impact than the standard Basic and Digest schemes.”
但是使用起來還是非常的方便的。因為 NTLM 連接是有狀態的,通常建議使用相對簡單的方法觸發NTLM 認證,比如GET或 HEAD, 而重用相同的連接來執行代價更大的方法,特別是它們包含請求實體,比如 POST或 PUT。
DefaultHttpClient httpclient = new DefaultHttpClient(); NTCredentials creds = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com"); httpclient.getCredentialsProvider().setCredentials(AuthScop .ANY, creds); HttpHost target = new HttpHost("www.microsoft.com", 80, "http"); // 保證相同的內容來用于執行邏輯相關的請求 HttpContext localContext = new BasicHttpContext(); // 首先執行簡便的方法。這會觸發NTLM認證 HttpGet httpget = new HttpGet("/ntlm-protected/info"); HttpResponse response1 = httpclient.execute(target, httpget localContext); HttpEntity entity1 = response1.getEntity(); if (entity1 != null) { entity1.consumeContent(); } //之后使用相同的內容(和連接)執行開銷大的方法。 HttpPost httppost = new HttpPost("/ntlm-protected/form"); httppost.setEntity(new StringEntity("lots and lots of data")) HttpResponse response2 = httpclient.execute(target, httppost, localContext); HttpEntity entity2 = response2.getEntity(); if (entity2 != null) { entity2.consumeContent(); }
稍后在研究一下jcifi和smb協議
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
