From be7d00feb489a6232b894d89db4306847393c54f Mon Sep 17 00:00:00 2001 From: clement Date: Thu, 8 Aug 2024 23:20:33 +0200 Subject: [PATCH] Fix DPoPInterceptor thread-safety - MessageDigest is not thread-safe, wrap in a ThreadLocal --- .../com/okta/sdk/impl/oauth2/DPoPInterceptor.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/impl/src/main/java/com/okta/sdk/impl/oauth2/DPoPInterceptor.java b/impl/src/main/java/com/okta/sdk/impl/oauth2/DPoPInterceptor.java index a42068eabea..263bf38fdce 100644 --- a/impl/src/main/java/com/okta/sdk/impl/oauth2/DPoPInterceptor.java +++ b/impl/src/main/java/com/okta/sdk/impl/oauth2/DPoPInterceptor.java @@ -62,15 +62,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 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 jwk; @@ -119,7 +118,7 @@ private void processRequest(HttpRequest request, boolean tokenRequest) { //already authenticated, need to replace Authorization header prefix and set ath claim String token = authorization.getValue().replaceFirst("^Bearer ", ""); 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