Skip to content

Commit

Permalink
Fix DPoPInterceptor thread-safety (#1534) (#1551)
Browse files Browse the repository at this point in the history
- MessageDigest is not thread-safe, wrap in a ThreadLocal

Co-authored-by: Clément Denis <[email protected]>
  • Loading branch information
arvindkrishnakumar-okta and clementdenis authored Sep 3, 2024
1 parent c4a0037 commit ddd7810
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions impl/src/main/java/com/okta/sdk/impl/oauth2/DPoPInterceptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,14 @@ public class DPoPInterceptor implements ExecChainHandler {
private static final String DPOP_HEADER = "DPoP";
//nonce is valid for 24 hours, but can only refresh it when doing a token request => start refreshing after 22 hours
private static final int NONCE_VALID_SECONDS = 60 * 60 * 22;
private static final MessageDigest SHA256; //required to sign ath claim

static {
//MessageDigest is not thread-safe, need one per thread
private static final ThreadLocal<MessageDigest> SHA256 = ThreadLocal.withInitial(() -> {
try {
SHA256 = MessageDigest.getInstance("SHA-256");
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
});

//if null, means dpop is not enabled yet
private PrivateJwk<PrivateKey, PublicKey, ?> jwk;
Expand Down Expand Up @@ -118,7 +117,7 @@ private void processRequest(HttpRequest request, boolean tokenRequest) {
//the DPoP prefix might already be set if the request is retried
String token = StringUtils.substringAfter(authorization.getValue(), " ");
request.setHeader("Authorization", DPOP_HEADER + " " + token);
byte[] ath = SHA256.digest(token.getBytes(StandardCharsets.US_ASCII));
byte[] ath = SHA256.get().digest(token.getBytes(StandardCharsets.US_ASCII));
builder.claim("ath", Encoders.BASE64URL.encode(ath));
} else if (tokenRequest && nonce != null) {
//still in handshake, need to set nonce
Expand Down

0 comments on commit ddd7810

Please sign in to comment.