首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java訪問Windows身份驗證頁面:Basic Auth與HttpClient實現詳解

     編輯:程式設計綜合問答

瀏覽器彈出的「Windows安全性」對話框實為**HTTP Basic Authentication**。Java程序訪問此類頁面,需在請求頭中添加`Authorization: Basic `。本文提供完整實現代碼。

核心原理

  • 服務器返回 `401 Unauthorized` + `WWW-Authenticate: Basic realm="..."`。
  • 客戶端需在後續請求頭加入 `Authorization: Basic ` + `Base64(username:password)`。
  • 無需處理Cookie/Session,無狀態認證。

原生HttpURLConnection實現


import java.io.*;
import java.net.*;
import java.util.Base64; // Java 8+

public class BasicAuthClient {
    public static String getContent(String urlStr, String username, String password) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        // 1. 構建 Basic Auth Header
        String auth = username + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        conn.setRequestProperty("Authorization", "Basic " + encodedAuth);
        
        // 2. 設置通用請求屬性
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);
        conn.setRequestProperty("User-Agent", "Java BasicAuth Client");
        
        // 3. 處理響應
        int responseCode = conn.getResponseCode();
        InputStream is = (responseCode >= 200 && responseCode < 300) ? 
                         conn.getInputStream() : conn.getErrorStream();
        
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) sb.append(line).append('\n');
            return sb.toString();
        }
    }
    
    public static void main(String[] args) throws IOException {
        String content = getContent("https://192.168.1.100/protected", "admin", "password123");
        System.out.println(content);
    }
}

Apache HttpClient 4.5+ 實現(推薦生產環境)



    org.apache.httpcomponents
    httpclient
    4.5.14


import org.apache.http.auth.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.auth.*;
import org.apache.http.util.EntityUtils;

public class HttpClientBasicAuth {
    public static String getContent(String url, String user, String pass) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(user, pass)
        );
        
        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credsProvider)
                .setDefaultAuthSchemeRegistry(new RegistryBuilder()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .build())
                .build()) {
            
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        }
    }
}

進階場景處理

場景處理方式
NTLM/Kerberos認證HttpClient配置`NTCredentials`/`KerberosCredentials`,需域環境支持
重定向攜帶認證HttpClient默認處理;HttpURLConnection需手動跟隨重定向並重新設置Header
代理服務器認證設置`Proxy` + `CredentialsProvider` for proxy scope
雙向SSL + Basic Auth配置`SSLContext`客戶端證書 + Basic Auth Header

安全警示

  • 🚫 **絕不** 在URL中嵌入憑證(`https://user:pass@host`),日志/歷史記錄洩露風險極高。
  • 🚫 **絕不** 硬編碼密碼,使用配置中心/環境變量/密碼管理器。
  • ✅ 僅在HTTPS傳輸下使用Basic Auth,否則Base64極易解碼竊取。
  • ✅ 優先考慮Token/OAuth2/JWT等現代認證方案替代Basic Auth。
Windows身份驗證彈窗 = HTTP Basic Auth,Java只需在請求頭加入Base64編碼的用戶名密碼即可訪問。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved