java http 验证,Java 11 HttpClient未发送基本身份验证

I wrote the following HttpClient code, and it did not result in an Authorization header being sent to the server:

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();

}

I'm getting an HTTP 401 error from the service I'm calling. In my case, it's the Atlassian Jira Cloud API.

I have confirmed that my getPasswordAuthentication() method is not being invoked by HttpClient.

Why isn't it working, and what should I do instead?

解决方案

The service I was calling (in this case, Atlassian's Jira Cloud API) supports both Basic and OAuth authentication. I was attempting to use HTTP Basic, but it sends back an auth challenge for OAuth.

As of the current JDK 11, HttpClient does not send Basic credentials until challenged for them with a WWW-Authenticate header from the server. Further, the only type of challenge it understands is for Basic authentication. The relevant JDK code is here (complete with TODO for supporting more than Basic auth) if you'd like to take a look.

In the meantime, my remedy has been to bypass HttpClient's authentication API and to create and send the Basic Authorization header myself:

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());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值