From 3b3356e81bd4c632ef92896f1d55cc16fe25041e Mon Sep 17 00:00:00 2001 From: shaofengshi Date: Mon, 8 May 2017 10:43:28 +0800 Subject: [PATCH] KYLIN-2589 MessageDigest is not thread-safe --- .../rest/security/KylinAuthenticationProvider.java | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/server-base/src/main/java/org/apache/kylin/rest/security/KylinAuthenticationProvider.java b/server-base/src/main/java/org/apache/kylin/rest/security/KylinAuthenticationProvider.java index d0dd06a..88fc514 100644 --- a/server-base/src/main/java/org/apache/kylin/rest/security/KylinAuthenticationProvider.java +++ b/server-base/src/main/java/org/apache/kylin/rest/security/KylinAuthenticationProvider.java @@ -55,27 +55,34 @@ public class KylinAuthenticationProvider implements AuthenticationProvider { //Embedded authentication provider private AuthenticationProvider authenticationProvider; - MessageDigest md = null; + private final ThreadLocal messageDigestThreadLocal = new ThreadLocal<>(); public KylinAuthenticationProvider(AuthenticationProvider authenticationProvider) { super(); Assert.notNull(authenticationProvider, "The embedded authenticationProvider should not be null."); this.authenticationProvider = authenticationProvider; - try { - md = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Failed to init Message Digest ", e); - } + } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authed = null; - Cache userCache = cacheManager.getCache("UserCache"); + MessageDigest md = messageDigestThreadLocal.get(); + if (md == null) { + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Failed to init Message Digest ", e); + } + + messageDigestThreadLocal.set(md); + } + md.reset(); byte[] hashKey = md.digest((authentication.getName() + authentication.getCredentials()).getBytes()); String userKey = Arrays.toString(hashKey); + Cache userCache = cacheManager.getCache("UserCache"); Element authedUser = userCache.get(userKey); if (null != authedUser) { authed = (Authentication) authedUser.getObjectValue(); -- 2.7.2