Java 11 HttpClient not sending basic authentication

前端 未结 1 1689
星月不相逢
星月不相逢 2021-02-19 22:27

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[] a         


        
相关标签:
1条回答
  • 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)
提交回复
热议问题