java - Java 11 HttpClient 未发送基本身份验证
问题描述
我编写了以下 HttpClient 代码,它没有导致将Authorization
标头发送到服务器:
public static void main(String[] args) {
var client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
})
.version(HttpClient.Version.HTTP_1_1)
.build();
var request = HttpRequest.newBuilder()
.uri("https://service-that-needs-auth.example/")
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
我从正在调用的服务中收到 HTTP 401 错误。就我而言,它是 Atlassian Jira Cloud API。
我已经确认getPasswordAuthentication()
HttpClient 没有调用我的方法。
为什么它不起作用,我应该怎么做?
解决方案
我调用的服务(在本例中为 Atlassian 的 Jira Cloud API)同时支持基本身份验证和 OAuth 身份验证。我试图使用 HTTP Basic,但它向 OAuth 发送了一个身份验证挑战。
从当前的 JDK 11 开始,HttpClient 不会发送基本凭据,直到使用来自服务器的 WWW-Authenticate 标头对它们进行质询。此外,它理解的唯一挑战类型是基本身份验证。如果您想看一下,相关的 JDK 代码在这里(包含 TODO 以支持更多基本身份验证)。
与此同时,我的补救措施是绕过 HttpClient 的身份验证 API,并自己创建和发送 Basic Authorization 标头:
public static void main(String[] args) {
var client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
var request = HttpRequest.newBuilder()
.uri(new URI("https://service-that-needs-auth.example/"))
.header("Authorization", basicAuth("username", "password"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
private static String basicAuth(String username, String password) {
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
}
推荐阅读
- html - 显示列表项:flex;并标记
- java - 使用预定义的 java 方法查找数组中的最大数
- java - JavaFx 文本中心位于 X 和 Y
- java - Java 和 OPENSSL
- python - 无法将数据拟合到 HMM-Learn 模型(Python3.9)
- c++ - 如何将一组图像拼接成 MxN 图像拼贴
- c++ - 无法 fnid grpcpp/grpcpp.h - 如何包含它?
- javascript - 两个对象数组的差异与lodash
- elastic-stack - 如何通过命令行工具在 Filebeats 中动态添加字段?
- java - 如何在我的类中使用复制构造函数和静态字段?