1. Overview
1.概述
In this short tutorial, we’ll take a look at basic authentication. We’ll see how it works and configure the Java HttpClient to use this kind of authentication.
在这个简短的教程中,我们将看一下基本认证。我们将看到它是如何工作的,并配置Java HttpClient以使用这种认证。
2. Basic Authentication
2.基本认证
Basic authentication is a simple authentication method. Clients can authenticate via username and password. These credentials are sent in the Authorization HTTP header in a specific format. It begins with the Basic keyword, followed by a base64-encoded value of username:password. The colon character is important here. The header should strictly follow this format.
基本认证是一种简单的认证方法。客户端可以通过用户名和密码进行认证。这些证书在Authorization HTTP头中以特定格式发送。它以Basic关键字开始,后面是一个base64编码的username:password值。这里的冒号字符很重要。头部应该严格遵循这个格式。
For example, to authenticate with baeldung username and HttpClient password we must send this header:
例如,要用baeldung用户名和HttpClient密码进行认证,我们必须发送这个头。
Basic YmFlbGR1bmc6SHR0cENsaWVudA==
We can verify it by using a base64 decoder and checking the decoded result.
我们可以通过使用base64解码器和检查解码的结果来验证。
3. Java HttpClient
3.Java HttpClient[/strong
Java 9 introduced a new HttpClient as an incubated module which was standardized in Java 11. We’ll use Java 11, so we can simply import it from the java.net.http package without any extra configuration or dependencies.
Java 9引入了一个新的HttpClient作为孵化模块,在Java 11中得到了标准化。我们将使用Java 11,所以我们可以简单地从java.net.http包中导入它,而无需任何额外的配置或依赖。
Let’s start by executing a simple GET request without any authentication for now:
让我们开始执行一个简单的GET请求,暂时不需要任何认证:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(new URI("https://postman-echo.com/get"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
logger.info("Status {}", response.statusCode());
Firstly, we create an HttpClient, which can be used to execute HTTP requests. Secondly, we create an HttpRequest using the builder design pattern. The GET method sets the HTTP method of the request. The uri method sets the URL where we would like to send the request.
首先,我们创建一个HttpClient,它可以用来执行HTTP请求。其次,我们使用builder设计模式创建一个HttpRequest。GET方法设置请求的 HTTP 方法。uri方法设置我们想发送请求的URL。
After that, we send the request using our client. The second parameter of the send method is a response body handler. This tells the client that we would like to treat the response body as a String.
之后,我们使用我们的客户端发送该请求。send方法的第二个参数是response body handler。这告诉客户端,我们想把响应体当作String。
Let’s run our application and check the logs. The output should look like this:
让我们运行我们的应用程序并检查日志。输出应该是这样的。
INFO com.baeldung.httpclient.basicauthentication.HttpClientBasicAuthentication - Status 200
We see that the HTTP status is 200, meaning our request was successful. After this, let’s see how we can handle authentication.
我们看到HTTP状态是200,这意味着我们的请求是成功的。在这之后,让我们看看我们如何处理认证。
4. Using HttpClient Authenticator
4.使用HttpClient身份验证器
Before we configure authentication we need an URL to test it. Let’s use a Postman Echo endpoint that requires authentication. Firstly, change the previous URL to this and run the application again:
在我们配置认证之前,我们需要一个URL来测试它。让我们使用一个需要认证的Postman Echo端点。首先,将之前的URL改为这个,然后再次运行应用程序。
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(new URI("https://postman-echo.com/basic-auth"))
.build();
Let’s check the logs and look for the status code. This time we received HTTP status 401 “Unauthorized”. This response code means that the endpoint requires authentication but the client didn’t send any credentials.
让我们检查一下日志,找找状态代码。这次我们收到HTTP状态401 “未授权”。这个响应代码意味着端点需要认证,但客户端没有发送任何凭证。
Let’s change our client so that it sends the required authentication data. We can do this by configuring the HttpClient Builder and our client will use the credentials we set up. This endpoint accepts the username “postman” with the password “password”. Let’s add an authenticator to our client:
让我们改变我们的客户端,以便它能够发送所需的认证数据。我们可以通过配置HttpClient Builder来做到这一点,我们的客户端将使用我们设置的凭证。这个端点接受用户名“postman”和密码“password”。让我们为我们的客户端添加一个认证器。
HttpClient client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build();
Let’s run the application again. Now the request is successful and we receive HTTP status 200.
让我们再次运行该应用程序。现在请求成功了,我们收到HTTP状态200。
5. Authenticate Using HTTP Headers
5.使用HTTP标头进行认证
We can use another approach to access endpoints that require authentication. We learned from previous sections how the Authorization header is constructed, so we can set its value manually. Although this has to be done per request instead of setting it once via an authenticator.
我们可以使用另一种方法来访问需要认证的端点。我们从前面的章节中了解到Authorization头是如何构建的,因此我们可以手动设置其值。尽管这必须在每个请求中进行,而不是通过认证器设置一次。
Let’s remove the authenticator and see how we can set the request headers. We need to construct the header value using base64 encoding:
让我们删除验证器,看看我们如何设置请求头。我们需要使用base64编码来构造头信息值。
private static final String getBasicAuthenticationHeader(String username, String password) {
String valueToEncode = username + ":" + password;
return "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
}
Let’s set this value for the Authorization header and run the application:
让我们为Authorization头设置这个值并运行应用程序。
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(new URI("https://postman-echo.com/basic-auth"))
.header("Authorization", getBasicAuthenticationHeader("postman", "password"))
.build();
Our request is successful which means that we constructed and set the header value correctly.
我们的请求是成功的,这意味着我们正确地构建和设置了头信息值。
6. Conclusion
6.结论
In this short tutorial, we saw what is basic authentication and how it works. We used the Java HttpClient with basic authentication by setting an authenticator for it. We used a different approach to authenticate by setting the HTTP header manually.
在这个简短的教程中,我们看到了什么是基本认证以及它是如何工作的。我们通过为Java HttpClient设置一个authenticator来使用基本认证。我们使用了一种不同的方法,通过手动设置HTTP头来进行认证。
As always, the source code for these examples is available over on GitHub.
一如既往,这些示例的源代码可在GitHub上获取。