Skip to content

Implement HTTP Digest Access Authentication #2089

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 39 additions & 33 deletions client/src/main/java/org/asynchttpclient/Realm.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import static org.asynchttpclient.util.StringUtils.appendBase16;
import static org.asynchttpclient.util.StringUtils.toHexString;
import org.asynchttpclient.util.MessageDigestUtils;

/**
* This class is required when authentication is needed. The class support
Expand Down Expand Up @@ -452,62 +453,65 @@ public Builder parseProxyAuthenticateHeader(String headerLine) {
return this;
}

/**
* Extracts the value of a token from a WWW-Authenticate or Proxy-Authenticate header line.
* Example: match('Digest realm="test", nonce="abc"', "realm") returns "test"
*/
private static @Nullable String match(String headerLine, String token) {
if (headerLine == null || token == null) return null;
String pattern = token + "=\"";
int start = headerLine.indexOf(pattern);
if (start == -1) return null;
start += pattern.length();
int end = headerLine.indexOf('"', start);
if (end == -1) return null;
return headerLine.substring(start, end);
}

private void newCnonce(MessageDigest md) {
byte[] b = new byte[8];
ThreadLocalRandom.current().nextBytes(b);
b = md.digest(b);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MD5 =16 bytes; SHA-256 = 32 bytes;
rfc7616 doesn’t forbid long nonces... but wont the headers that big can be unwieldy, especially if you’re proxying or logging??

cnonce = toHexString(b);
}

/**
* TODO: A Pattern/Matcher may be better.
*/
private static @Nullable String match(String headerLine, String token) {
if (headerLine == null) {
return null;
}

int match = headerLine.indexOf(token);
if (match <= 0) {
return null;
}

// = to skip
match += token.length() + 1;
int trailingComa = headerLine.indexOf(',', match);
String value = headerLine.substring(match, trailingComa > 0 ? trailingComa : headerLine.length());
value = value.length() > 0 && value.charAt(value.length() - 1) == '"'
? value.substring(0, value.length() - 1)
: value;
return value.charAt(0) == '"' ? value.substring(1) : value;
}

private static byte[] md5FromRecycledStringBuilder(StringBuilder sb, MessageDigest md) {
private static byte[] digestFromRecycledStringBuilder(StringBuilder sb, MessageDigest md) {
md.update(StringUtils.charSequence2ByteBuffer(sb, ISO_8859_1));
Copy link
Contributor

@pratt4 pratt4 May 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can utf-8 be implemented?

image

sb.setLength(0);
return md.digest();
}

private static MessageDigest getDigestInstance(String algorithm) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the server sends multiple algos (eg: md5, sha256..eg)
then public Builder parseWWWAuthenticateHeader(String headerLine) --- can pick the first algo (here m5 can be chosen even if sha256 is present )

it should choose the algo based on strength right??
image

if (algorithm == null || "MD5".equalsIgnoreCase(algorithm) || "MD5-sess".equalsIgnoreCase(algorithm)) {
return MessageDigestUtils.pooledMd5MessageDigest();
} else if ("SHA-256".equalsIgnoreCase(algorithm) || "SHA-256-sess".equalsIgnoreCase(algorithm)) {
return MessageDigestUtils.pooledSha256MessageDigest();
} else if ("SHA-512-256".equalsIgnoreCase(algorithm) || "SHA-512-256-sess".equalsIgnoreCase(algorithm)) {
Copy link
Contributor

@pratt4 pratt4 May 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will it handle "SHA-512/256" ??
some server might send with / 's
and even "SHA-512/256" is mentioned in standard names docs... https://docs.oracle.com/en/java/javase/12/docs/specs/security/standard-names.html

return MessageDigestUtils.pooledSha512_256MessageDigest();
} else {
throw new UnsupportedOperationException("Digest algorithm not supported: " + algorithm);
}
}

private byte[] ha1(StringBuilder sb, MessageDigest md) {
// if algorithm is "MD5" or is unspecified => A1 = username ":" realm-value ":"
// passwd
// if algorithm is "MD5-sess" => A1 = MD5( username-value ":" realm-value ":"
// passwd ) ":" nonce-value ":" cnonce-value

sb.append(principal).append(':').append(realmName).append(':').append(password);
byte[] core = md5FromRecycledStringBuilder(sb, md);
byte[] core = digestFromRecycledStringBuilder(sb, md);

if (algorithm == null || "MD5".equals(algorithm)) {
if (algorithm == null || "MD5".equalsIgnoreCase(algorithm) || "SHA-256".equalsIgnoreCase(algorithm) || "SHA-512-256".equalsIgnoreCase(algorithm)) {
// A1 = username ":" realm-value ":" passwd
return core;
}
if ("MD5-sess".equals(algorithm)) {
// A1 = MD5(username ":" realm-value ":" passwd ) ":" nonce ":" cnonce
if ("MD5-sess".equalsIgnoreCase(algorithm) || "SHA-256-sess".equalsIgnoreCase(algorithm) || "SHA-512-256-sess".equalsIgnoreCase(algorithm)) {
// A1 = HASH(username ":" realm-value ":" passwd ) ":" nonce ":" cnonce
appendBase16(sb, core);
sb.append(':').append(nonce).append(':').append(cnonce);
return md5FromRecycledStringBuilder(sb, md);
return digestFromRecycledStringBuilder(sb, md);
}

throw new UnsupportedOperationException("Digest algorithm not supported: " + algorithm);
}

Expand All @@ -526,7 +530,7 @@ private byte[] ha2(StringBuilder sb, String digestUri, MessageDigest md) {
throw new UnsupportedOperationException("Digest qop not supported: " + qop);
}

return md5FromRecycledStringBuilder(sb, md);
return digestFromRecycledStringBuilder(sb, md);
}

private void appendMiddlePart(StringBuilder sb) {
Expand All @@ -553,7 +557,7 @@ private void newResponse(MessageDigest md) {
appendMiddlePart(sb);
appendBase16(sb, ha2);

byte[] responseDigest = md5FromRecycledStringBuilder(sb, md);
byte[] responseDigest = digestFromRecycledStringBuilder(sb, md);
response = toHexString(responseDigest);
}
}
Expand All @@ -567,7 +571,9 @@ public Realm build() {

// Avoid generating
if (isNonEmpty(nonce)) {
MessageDigest md = pooledMd5MessageDigest();
// Defensive: if algorithm is null, default to MD5
String algo = (algorithm != null) ? algorithm : "MD5";
MessageDigest md = getDigestInstance(algo);
newCnonce(md);
newResponse(md);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
Expand Down Expand Up @@ -70,9 +69,7 @@ public static String computeRealmURI(Uri uri, boolean useAbsoluteURI, boolean om
}

private static String computeDigestAuthentication(Realm realm, Uri uri) {

String realmUri = computeRealmURI(uri, realm.isUseAbsoluteURI(), realm.isOmitQuery());

StringBuilder builder = new StringBuilder().append("Digest ");
append(builder, "username", realm.getPrincipal(), true);
append(builder, "realm", realm.getRealmName(), true);
Expand All @@ -81,22 +78,17 @@ private static String computeDigestAuthentication(Realm realm, Uri uri) {
if (isNonEmpty(realm.getAlgorithm())) {
append(builder, "algorithm", realm.getAlgorithm(), false);
}

append(builder, "response", realm.getResponse(), true);

if (realm.getOpaque() != null) {
append(builder, "opaque", realm.getOpaque(), true);
}

if (realm.getQop() != null) {
append(builder, "qop", realm.getQop(), false);
// nc and cnonce only sent if server sent qop
append(builder, "nc", realm.getNc(), false);
append(builder, "cnonce", realm.getCnonce(), true);
}
// RFC7616: userhash parameter (optional, not implemented yet)
builder.setLength(builder.length() - 2); // remove tailing ", "

// FIXME isn't there a more efficient way?
return new String(StringUtils.charSequence2Bytes(builder, ISO_8859_1), StandardCharsets.UTF_8);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,88 @@ public final class MessageDigestUtils {
}
});

private static final ThreadLocal<MessageDigest> SHA256_MESSAGE_DIGESTS = ThreadLocal.withInitial(() -> {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new InternalError("SHA-256 not supported on this platform");
}
});

private static final ThreadLocal<MessageDigest> SHA512_256_MESSAGE_DIGESTS = ThreadLocal.withInitial(() -> {
try {
return MessageDigest.getInstance("SHA-512/256");
} catch (NoSuchAlgorithmException e) {
throw new InternalError("SHA-512/256 not supported on this platform");
}
});

private MessageDigestUtils() {
// Prevent outside initialization
}

public static MessageDigest pooledMd5MessageDigest() {
MessageDigest md = MD5_MESSAGE_DIGESTS.get();
/**
* Returns a pooled MessageDigest instance for the given algorithm name.
* Supported: "MD5", "SHA-1", "SHA-256", "SHA-512/256" (and aliases).
* The returned instance is thread-local and reset before use.
*
* @param algorithm the algorithm name (e.g., "MD5", "SHA-256", "SHA-512/256")
* @return a reset MessageDigest instance for the algorithm
* @throws IllegalArgumentException if the algorithm is not supported
*/
public static MessageDigest pooledMessageDigest(String algorithm) {
String alg = algorithm.replace("_", "-").toUpperCase();
MessageDigest md;
switch (alg) {
case "MD5":
md = MD5_MESSAGE_DIGESTS.get();
break;
case "SHA1":
case "SHA-1":
md = SHA1_MESSAGE_DIGESTS.get();
break;
case "SHA-256":
md = SHA256_MESSAGE_DIGESTS.get();
break;
case "SHA-512/256":
md = SHA512_256_MESSAGE_DIGESTS.get();
break;
default:
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Unsupported digest algorithm: " + algorithm, e);
}
}
md.reset();
return md;
}

/**
* @return a pooled, reset MessageDigest for MD5
*/
public static MessageDigest pooledMd5MessageDigest() {
return pooledMessageDigest("MD5");
}

/**
* @return a pooled, reset MessageDigest for SHA-1
*/
public static MessageDigest pooledSha1MessageDigest() {
MessageDigest md = SHA1_MESSAGE_DIGESTS.get();
md.reset();
return md;
return pooledMessageDigest("SHA-1");
}

/**
* @return a pooled, reset MessageDigest for SHA-256
*/
public static MessageDigest pooledSha256MessageDigest() {
return pooledMessageDigest("SHA-256");
}

/**
* @return a pooled, reset MessageDigest for SHA-512/256
*/
public static MessageDigest pooledSha512_256MessageDigest() {
return pooledMessageDigest("SHA-512/256");
}
}
51 changes: 49 additions & 2 deletions client/src/test/java/org/asynchttpclient/AuthTimeoutTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.asynchttpclient.test.ExtendedDigestAuthenticator;

import java.io.IOException;
import java.io.OutputStream;
Expand All @@ -39,7 +40,7 @@
import static org.asynchttpclient.test.TestUtils.ADMIN;
import static org.asynchttpclient.test.TestUtils.USER;
import static org.asynchttpclient.test.TestUtils.addBasicAuthHandler;
import static org.asynchttpclient.test.TestUtils.addDigestAuthHandler;
// import static org.asynchttpclient.test.TestUtils.addDigestAuthHandler;
import static org.asynchttpclient.test.TestUtils.addHttpConnector;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand All @@ -63,7 +64,8 @@ public void setUpGlobal() throws Exception {

server2 = new Server();
ServerConnector connector2 = addHttpConnector(server2);
addDigestAuthHandler(server2, configureHandler());
// Use DigestAuthHandler for server2 (digest tests), otherwise use default handler
server2.setHandler(new DigestAuthHandler());
server2.start();
port2 = connector2.getLocalPort();

Expand Down Expand Up @@ -181,6 +183,51 @@ public AbstractHandler configureHandler() throws Exception {
return new IncompleteResponseHandler();
}

// DigestAuthHandler for Digest tests (MD5 only, as in old Jetty default)
private static class DigestAuthHandler extends AbstractHandler {
private final String realm = "MyRealm";
private final String user = USER;
private final String password = ADMIN;
private final ExtendedDigestAuthenticator authenticator = new ExtendedDigestAuthenticator("MD5");
private final String nonce = ExtendedDigestAuthenticator.newNonce();

@Override
public void handle(String s, Request r, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String authz = request.getHeader("Authorization");
if (authz == null || !authz.startsWith("Digest ")) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", authenticator.createAuthenticateHeader(realm, nonce, false));
response.getOutputStream().close();
return;
}
String credentials = authz.substring("Digest ".length());
if (!user.equals(ExtendedDigestAuthenticator.parseCredentials(credentials).get("username"))) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", authenticator.createAuthenticateHeader(realm, nonce, true));
response.getOutputStream().close();
return;
}
boolean ok = ExtendedDigestAuthenticator.validateDigest(request.getMethod(), credentials, password);
if (!ok) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", authenticator.createAuthenticateHeader(realm, nonce, true));
response.getOutputStream().close();
return;
}
// Success: simulate incomplete response for timeout
response.setStatus(200);
OutputStream out = response.getOutputStream();
response.setIntHeader(CONTENT_LENGTH.toString(), 1000);
out.write(0);
out.flush();
try {
Thread.sleep(LONG_FUTURE_TIMEOUT + 100);
} catch (InterruptedException e) {
//
}
}
}

private static class IncompleteResponseHandler extends AbstractHandler {

@Override
Expand Down
Loading