Dontea
Dontea

Reputation: 51

Digest Authentication java.net.http.HttpClient

I'm trying to connect to a website protected with digest authentication. My credentials work fine if I try to log in via Insomnia or Firefox but I fail to get it to work in Java 17 (Insomnia's automatically generated Code also doesn't work).

I tried to follow and understand the following tutorials/docs:

https://www.baeldung.com/java-9-http-client

https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html

Both mention that Digest is supported, as far as I understand.

The result I get is always status code 401 & the expected header when digest auth fails:

www-authenticate=[Digest realm="api-realm", qop="auth", nonce="NONCE=="

Here is the current code. The method getPasswordAuthentication doesn't get executed:

public void checkIsAPIRunning() {

    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://the-site-I-try-to-connect-with:443/api/function"))
            .method("GET", HttpRequest.BodyPublishers.noBody()).build();
    HttpResponse<String> response = null;
    try {
        response = HttpClient.newBuilder().authenticator(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("user", "pass".toCharArray());
            }
        }).build().send(request, BodyHandlers.ofString());          
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Am I misunderstanding the docs? I'd appreciate any help or pointers :)

Upvotes: 5

Views: 2316

Answers (2)

ron190
ron190

Reputation: 1102

You have to implement the handshake algorithm, and I advise to use curl to validate the process first.

I did the implementation following this algorithm:

  1. Call the Digest endpoint: response is 401 with header www-authenticate
  2. Get params realm, qop and nonce from header www-authenticate
  3. Build HA1, HA2, response and digest header Authorization
  4. Call endpoint a second time with the header Authorization
  5. Response should be 200 OK

Digest implementation validated with Spring: https://github.com/ron190/jsql-injection/blob/master/model/src/main/java/com/jsql/util/DigestUtil.java

Inspired by following resources:

Upvotes: 2

taranion
taranion

Reputation: 671

Digest authentication is not supported directly by the new HttpClient - see here: https://bugs.openjdk.org/browse/JDK-8285888

You are expected to handle the authentication process yourself, it seems.

Upvotes: 1

Related Questions