Autenticação básica HttpClient
1. Visão geral
Este tutorial ilustrará comoconfigure Basic Authentication on the Apache HttpClient 4.
Se você quiser se aprofundar e aprender outras coisas legais que você pode fazer com o HttpClient - vá parathe main HttpClient tutorial.
Leitura adicional:
Tutorial HttpAsyncClient
Tutorial HttpAsyncClient - envie uma solicitação GET básica, use o cliente multiencadeado, configure o cliente com SSL e também com um proxy e, finalmente - faça autenticação.
Configuração avançada do HttpClient
Configurações HttpClient para casos de uso avançados.
2. Autenticação básica com a API
Vamos começar comthe standard way of configuring Basic Authentication on the HttpClient – via a 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));
Como podemos ver, não é difícil criar o cliente com um provedor de credenciais para configurá-lo com a autenticação básica.
Agora, para entender o queHttpClient realmente fará nos bastidores, precisaremos examinar os registros:
# ... 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
Todo oClient-Server communication is now clear:
-
o cliente envia a solicitação HTTP sem credenciais
-
o servidor envia de volta um desafio
-
o cliente negocia e identifica o esquema de autenticação correto
-
o cliente enviaa second Request, desta vez com credenciais
3. Autenticação básica preemptiva
Fora da caixa, oHttpClient não faz autenticação preemptiva. Em vez disso, isso deve ser uma decisão explícita tomada pelo cliente.
Primeiro,we need to create the HttpContext – pre-populating it with an authentication cache com o tipo certo de esquema de autenticação pré-selecionado. Isso significa que a negociação do exemplo anterior não é mais necessária -Basic Authentication is already chosen:
HttpHost targetHost = new HttpHost("localhost", 8082, "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
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
Agora podemos usar o cliente com o novo contexto esend the pre-authentication request:
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));
Vejamos os registros:
[main] DEBUG ... - Re-using cached 'basic' auth scheme for http://localhost:8082
[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:8082
[main] DEBUG ... >> Authorization: Basic dXNlcjE6dXNlcjFQYXNz
[main] DEBUG ... << HTTP/1.1 200 OK
[main] DEBUG ... - Authentication succeeded
Tudo parece bem:
-
o esquema "Autenticação básica" é pré-selecionado
-
a solicitação é enviada com o cabeçalhoAuthorization
-
o servidor responde com um200 OK
-
A autenticação foi bem-sucedida
4. Autenticação básica com cabeçalhos HTTP brutos
Autenticação básica preemptiva basicamente significa pré-envio do cabeçalhoAuthorization.
Então, em vez de passar pelo exemplo anterior bastante complexo para configurá-lo,we can take control of this header and construct it by hand:
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.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));
Vamos verificar se isso está funcionando corretamente:
[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
Portanto, embora não haja cache de autenticação,Basic Authentication still works correctly and we receive 200 OK.
5. Conclusão
Este artigo ilustrou várias maneiras de configurar e usar a autenticação básica com o Apache HttpClient 4.
Como sempre, o código apresentado neste artigo está disponívelover on Github. Este é um projeto baseado em Maven, portanto, deve ser fácil importar e executar como está.