256. Setting connection authentication

Typically, authentication to a server is accomplished using a username and password. In code form, this can be done by using the Authenticator class (this negotiates the credentials for HTTP authentication) and the PasswordAuthentication class (the holder for the username and password) together, as follows:

HttpClient client = HttpClient.newBuilder()
.authenticator(new Authenticator() {

@Override
protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(
"username",
"password".toCharArray());
}
})
.build();

Furthermore, the client can be used to send requests:

HttpRequest request = HttpRequest.newBuilder()
...
.build();

HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandlers.ofString());
Authenticator supports different authentication schemes (for example, basic or digest authentication).

Another solution consists of adding credentials in the header, as follows:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.header("Authorization", basicAuth("username", "password"))
...
.build();

HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandlers.ofString());

private static String basicAuth(String username, String password) {
return "Basic " + Base64.getEncoder().encodeToString(
(username + ":" + password).getBytes());
}

In the case of a Bearer authentication (HTTP bearer token), we do the following:

HttpRequest request = HttpRequest.newBuilder()
.header("Authorization",
"Bearer mT8JNMyWCG0D7waCHkyxo0Hm80YBqelv5SBL")
.uri(URI.create("https://gorest.co.in/public-api/users"))
.build();

We can also do this in the body of a POST request:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString("{"email":"[email protected]",
"password":"cityslicka"}"))
.uri(URI.create("https://reqres.in/api/login"))
.build();

HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandlers.ofString());
Different requests can use different credentials. Moreover, Authenticator provides a suite of methods (for example, getRequestingSite()) that are useful if we wish to find out what values should be provided. In production, the application should not provide the credentials in plaintext, like they were in these examples.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.151.164