基本身份验证-使用API​​但不使用计算的标头-为什么?

时间:2018-10-17 11:28:53

标签: java http-headers basic-authentication

作为我正在进行的重构的一部分,我试图用预先计算好的“身份验证”标头替换使用API​​进行Http基本身份验证的代码。

这对我来说对一个客户来说效果很好,但对另一个客户则不行,下面将对此进行详细介绍。 有了这个,我得到“需要授权!”错误。

您能帮我理解原因吗?据我了解,这两个选项应该相同,不是吗?

工作代码:

//Set credentials using the API:
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1","pswd1");
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(authScope, credentials);

//Init HttpClient:
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).useSystemProperties().build();

//Execute request
String fullURI = getCdrsRequestURI(fromTime, toTime, limit, startFromResultIndex); //Some http uri
HttpGet httpGet = new HttpGet(new URI(fullURI));

HttpResponse httpResponse = httpClient.execute(httpGet); //Returns 200 OK status

无效代码:

//Init HttpClient:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

String fullURI = getCdrsRequestURI(fromTime, toTime, limit, startFromResultIndex);
HttpGet httpGet = new HttpGet(new URI(fullURI));

//Set basic authentication header
String authStr = MessageFormat.format("{0}:{1}", "user1", "pswd1");
String encoding = Base64.getEncoder().encodeToString(authStr.getBytes("UTF-8"));
httpGet.setHeader("Authorization", "Basic " + encoding);

//Execute request
HttpResponse httpResponse = httpClient.execute(httpGet); //Returns 401 code

最诚挚的问候,

卡梅尔

0 个答案:

没有答案