HttpClient Basic Authentication基本认证

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1522)   2023-03-28 11:29:14

1.概述

本教程将说明如何在Apache HttpClient 4上配置基本身份验证
 

2.使用API​​进行基本身份验证

让我们从在HttpClient上配置基本认证的标准方式开始 - 通过CredentialsProvider

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
 = new UsernamePasswordCredentials("user1", "user1Pass");
provider.setCredentials(AuthScope.ANY, credentials);
  
HttpClient client = HttpClientBuilder.create()
  .setDefaultCredentialsProvider(provider)
  .build();
 
HttpResponse response = client.execute(
  new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
int statusCode = response.getStatusLine()
  .getStatusCode();
  
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

如您所见,使用凭证提供程序创建客户端以使用基本身份验证进行设置并不困难。

现在,要了解HttpClient实际上在幕后做些什么,我们需要查看日志

# ... request is sent with no credentials
[main] DEBUG ... - Authentication required
[main] DEBUG ... - localhost:8080 requested authentication
[main] DEBUG ... - Authentication schemes in the order of preference: 
  [negotiate, Kerberos, NTLM, Digest, Basic]
[main] DEBUG ... - Challenge for negotiate authentication scheme not available
[main] DEBUG ... - Challenge for Kerberos authentication scheme not available
[main] DEBUG ... - Challenge for NTLM authentication scheme not available
[main] DEBUG ... - Challenge for Digest authentication scheme not available
[main] DEBUG ... - Selected authentication options: [BASIC]
# ... the request is sent again - with credentials

整个客户端 - 服务器通信现在已经清楚

  • 客户端发送没有凭据的HTTP请求
  • 服务器发回一个挑战
  • 客户协商并确定正确的认证方案
  • 客户端发送第二个请求,这次是凭证

3.抢先式基本身份验证

开箱即用,HttpClient不会进行抢先认证 - 这必须由客户做出明确的决定。

首先,我们需要创建HttpContext - 使用预先选择的正确类型的身份验证方案预先填充身份验证缓存。这将意味着前面示例中的否定不再是必要的 - 已经选择了基本身份验证

HttpHost targetHost = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, 
  new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
 
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
 
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);

现在我们可以在新的上下文中使用客户端并发送预认证请求

HttpClient client = HttpClientBuilder.create().build();
response = client.execute(
  new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context);
 
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

我们来看看日志

[main] DEBUG ... - Re-using cached 'basic' auth scheme for http://localhost:8080
[main] DEBUG ... - Executing request GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
[main] DEBUG ... >> GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
[main] DEBUG ... >> Host: localhost:8080
[main] DEBUG ... >> Authorization: Basic dXNlcjE6dXNlcjFQYXNz
[main] DEBUG ... << HTTP/1.1 200 OK
[main] DEBUG ... - Authentication succeeded

一切看起来都OK:

  • “基本认证”方案是预选的
  • 该请求与授权标头一起发送
  • 服务器响应200 OK
  • 身份验证成功

4.使用原始HTTP头进行基本身份验证

抢先式基本认证基本上意味着预先发送授权报头。

因此,我们不必通过相当复杂的前一个示例来设置它,而是可以控制此标头并手动构建它:

HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(Charset.forName("ISO-8859-1")));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
 
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
 
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

让我们确保这个工作正常:

[main] DEBUG ... - Auth cache not set in the context
[main] DEBUG ... - Opening connection {}->http://localhost:8080
[main] DEBUG ... - Connecting to localhost/127.0.0.1:8080
[main] DEBUG ... - Executing request GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
[main] DEBUG ... - Proxy auth state: UNCHALLENGED
[main] DEBUG ... - http-outgoing-0 >> GET /spring-security-rest-basic-auth/api/foos/1 HTTP/1.1
[main] DEBUG ... - http-outgoing-0 >> Authorization: Basic dXNlcjE6dXNlcjFQYXNz
[main] DEBUG ... - http-outgoing-0 << HTTP/1.1 200 OK

因此,即使没有身份验证缓存,基本身份验证仍是正确执行,并200 OK发送回
 

5.总结

本文介绍了使用Apache HttpClient 4设置和使用基本身份验证的各种方法。

标签: httpclient Java
地址:https://www.leftso.com/article/400.html

相关阅读

HttpClient的RestTemplate - Java配置示例
Apache HttpClient 4.x 使用详解
httpclient4.5使用详解 httpclient 4.5 post传递json参数
在本教程中 - 我们将使用HttpClient 4进行POST - 首先使用授权,然后使用流畅的HttpClient API。最后 - 我们将讨论如何使用HttpClient上传文件。
HttpClient Basic Authentication基本认证,本教程将说明如何在Apache HttpClient 4上配置基本身份验证。
本文将展示如何使用“接受所有”SSL支持来配置Apache HttpClient 4。目标很简单 - 使用没有有效证书的HTTPS URL。
HttpClient 4 按照POST重定向请求,本快速教程将展示如何配置Apache HttpClient 4以自动遵循POST请求的重定向。
Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类
1.概述本教程将重点介绍如何使用Apache HttpClient 4发送自定义Cookie
java编程中采用Apache common.httpclient方式模拟POST请求