Author: lquack
Date: Mon Jul 25 14:13:36 2016
New Revision: 1754010

URL: http://svn.apache.org/viewvc?rev=1754010&view=rev
Log:
QPID-7198: [Java Broker] Make LDAP and OAUTH2 Authentication Providers cache 
authentication results for a configurable time period

Added:
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/CryptoUtil.java
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/CachingAuthenticationProvider.java
Modified:
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerImpl.java
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProvider.java
    
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImpl.java
    
qpid/java/trunk/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImplTest.java

Added: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/CryptoUtil.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/CryptoUtil.java?rev=1754010&view=auto
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/CryptoUtil.java
 (added)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/CryptoUtil.java
 Mon Jul 25 14:13:36 2016
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.qpid.server.security;
+
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import javax.xml.bind.DatatypeConverter;
+
+public class CryptoUtil
+{
+    private static final String UTF8 = StandardCharsets.UTF_8.name();
+
+    public static String sha256Hex(final String... content)
+    {
+        MessageDigest md;
+        try
+        {
+            md = MessageDigest.getInstance("SHA-256");
+        }
+        catch (NoSuchAlgorithmException e)
+        {
+            throw new RuntimeException("JVM is non compliant. Seems to not 
support SHA-256.");
+        }
+
+        byte[] credentialDigest;
+        try
+        {
+            for (String part : content)
+            {
+                md.update(part.getBytes(UTF8));
+            }
+            credentialDigest = md.digest();
+        }
+        catch (UnsupportedEncodingException e)
+        {
+            throw new RuntimeException("JVM is non compliant. Seems to not 
support UTF-8.");
+        }
+        return DatatypeConverter.printHexBinary(credentialDigest);
+    }
+
+}

Added: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/CachingAuthenticationProvider.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/CachingAuthenticationProvider.java?rev=1754010&view=auto
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/CachingAuthenticationProvider.java
 (added)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/CachingAuthenticationProvider.java
 Mon Jul 25 14:13:36 2016
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.qpid.server.security.auth.manager;
+
+import org.apache.qpid.server.model.AuthenticationProvider;
+import org.apache.qpid.server.model.ManagedContextDefault;
+
+public interface CachingAuthenticationProvider<X extends 
AuthenticationProvider<X>> extends AuthenticationProvider<X>
+{
+    String AUTHORISATION_CACHE_MAX_SIZE = "qpid.auth.cache.size";
+    @SuppressWarnings("unused")
+    @ManagedContextDefault(name = AUTHORISATION_CACHE_MAX_SIZE,
+            description = "Upper bound of authentication results the 
AuthenticationProvider will cache.")
+    long DEFAULT_AUTHORISATION_CACHE_MAX_SIZE = 100;
+
+    String AUTHORISATION_CACHE_EXPIRATION_TIME = 
"qpid.auth.cache.expirationTime";
+    @SuppressWarnings("unused")
+    @ManagedContextDefault(name = AUTHORISATION_CACHE_EXPIRATION_TIME,
+            description = "How long cached credentials are valid in seconds.")
+    long DEFAULT_AUTHORISATION_CACHE_EXPIRATION_TIME = 10 * 60;
+}

Modified: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java?rev=1754010&r1=1754009&r2=1754010&view=diff
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java
 (original)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java
 Mon Jul 25 14:13:36 2016
@@ -22,7 +22,6 @@ package org.apache.qpid.server.security.
 
 import java.util.List;
 
-import org.apache.qpid.server.model.AuthenticationProvider;
 import org.apache.qpid.server.model.DerivedAttribute;
 import org.apache.qpid.server.model.ManagedAttribute;
 import org.apache.qpid.server.model.ManagedContextDefault;
@@ -34,7 +33,7 @@ import org.apache.qpid.server.model.Trus
                 type = "SimpleLDAP",
                 description = 
SimpleLDAPAuthenticationManager.CLASS_DESCRIPTION )
 public interface SimpleLDAPAuthenticationManager<X extends 
SimpleLDAPAuthenticationManager<X>>
-        extends AuthenticationProvider<X>,
+        extends CachingAuthenticationProvider<X>,
                 UsernamePasswordAuthenticationProvider<X>,
                 PreferencesSupportingAuthenticationProvider
 {

Modified: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerImpl.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerImpl.java?rev=1754010&r1=1754009&r2=1754010&view=diff
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerImpl.java
 (original)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerImpl.java
 Mon Jul 25 14:13:36 2016
@@ -33,6 +33,9 @@ import java.util.Hashtable;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 
 import javax.naming.AuthenticationException;
 import javax.naming.Context;
@@ -55,8 +58,9 @@ import javax.security.sasl.AuthorizeCall
 import javax.security.sasl.SaslException;
 import javax.security.sasl.SaslServer;
 
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
 import com.google.common.util.concurrent.ListenableFuture;
-import org.apache.qpid.server.security.group.GroupPrincipal;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -67,6 +71,7 @@ import org.apache.qpid.server.model.Conf
 import org.apache.qpid.server.model.ManagedAttributeField;
 import org.apache.qpid.server.model.ManagedObjectFactoryConstructor;
 import org.apache.qpid.server.model.TrustStore;
+import org.apache.qpid.server.security.CryptoUtil;
 import org.apache.qpid.server.security.auth.AuthenticationResult;
 import 
org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus;
 import org.apache.qpid.server.security.auth.UsernamePrincipal;
@@ -74,6 +79,7 @@ import org.apache.qpid.server.security.a
 import 
org.apache.qpid.server.security.auth.manager.ldap.LDAPSSLSocketFactoryGenerator;
 import org.apache.qpid.server.security.auth.sasl.plain.PlainPasswordCallback;
 import org.apache.qpid.server.security.auth.sasl.plain.PlainSaslServer;
+import org.apache.qpid.server.security.group.GroupPrincipal;
 import 
org.apache.qpid.server.util.CipherSuiteAndProtocolRestrictingSSLSocketFactory;
 import org.apache.qpid.server.util.ParameterizedTypes;
 import org.apache.qpid.server.util.StringUtil;
@@ -142,6 +148,8 @@ public class SimpleLDAPAuthenticationMan
     private List<String> _tlsCipherSuiteWhiteList;
     private List<String> _tlsCipherSuiteBlackList;
 
+    private Cache<String, AuthenticationResult> _authenticationCache;
+
     /**
      * Dynamically created SSL Socket Factory implementation.
      */
@@ -186,6 +194,19 @@ public class SimpleLDAPAuthenticationMan
         _tlsProtocolBlackList = getContextValue(List.class, 
ParameterizedTypes.LIST_OF_STRINGS, 
CommonProperties.QPID_SECURITY_TLS_PROTOCOL_BLACK_LIST);
         _tlsCipherSuiteWhiteList = getContextValue(List.class, 
ParameterizedTypes.LIST_OF_STRINGS, 
CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_WHITE_LIST);
         _tlsCipherSuiteBlackList = getContextValue(List.class, 
ParameterizedTypes.LIST_OF_STRINGS, 
CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_BLACK_LIST);
+
+        Long cacheMaxSize = getContextValue(Long.class, 
AUTHORISATION_CACHE_MAX_SIZE);
+        Long cacheExpirationTime = getContextValue(Long.class, 
AUTHORISATION_CACHE_EXPIRATION_TIME);
+        if (cacheMaxSize == null || cacheMaxSize <= 0 || cacheExpirationTime 
== null || cacheExpirationTime <= 0)
+        {
+            _logger.debug("disabling authentication result caching");
+            cacheMaxSize = 0L;
+            cacheExpirationTime = 1L;
+        }
+        _authenticationCache = CacheBuilder.newBuilder()
+                                           .maximumSize(cacheMaxSize)
+                                           
.expireAfterWrite(cacheExpirationTime, TimeUnit.SECONDS)
+                                           .build();
     }
 
     @Override
@@ -320,21 +341,22 @@ public class SimpleLDAPAuthenticationMan
     @Override
     public AuthenticationResult authenticate(String username, String password)
     {
-        String nameFromId;
+        return getOrLoadAuthenticationResult(username, password);
+    }
+
+    private AuthenticationResult doLDAPNameAuthentication(String userId, 
String password)
+    {
+        final String name;
         try
         {
-            nameFromId = getNameFromId(username);
+            name = getNameFromId(userId);
         }
         catch (NamingException e)
         {
-            _logger.warn("Retrieving LDAP name for user '{}' resulted in 
error.", username, e);
+            _logger.warn("Retrieving LDAP name for user '{}' resulted in 
error.", userId, e);
             return new 
AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
         }
-        return doLDAPNameAuthentication(nameFromId, password);
-    }
 
-    private AuthenticationResult doLDAPNameAuthentication(String name, String 
password)
-    {
         if(name == null)
         {
             //The search didn't return anything, class as not-authenticated 
before it NPEs below
@@ -387,6 +409,26 @@ public class SimpleLDAPAuthenticationMan
         }
     }
 
+    private AuthenticationResult getOrLoadAuthenticationResult(final String 
userId, final String password)
+    {
+        String credentialDigest = CryptoUtil.sha256Hex(userId, password);
+        try
+        {
+            return _authenticationCache.get(credentialDigest, new 
Callable<AuthenticationResult>()
+            {
+                @Override
+                public AuthenticationResult call()
+                {
+                    return doLDAPNameAuthentication(userId, password);
+                }
+            });
+        }
+        catch (ExecutionException e)
+        {
+            throw new RuntimeException("Unexpected checked Exception while 
authenticating", e.getCause());
+        }
+    }
+
     private boolean isGroupSearchRequired()
     {
         if (isSpecified(getGroupAttributeName()))
@@ -618,33 +660,25 @@ public class SimpleLDAPAuthenticationMan
         @Override
         public void handle(Callback[] callbacks) throws IOException, 
UnsupportedCallbackException
         {
-            String name = null;
+            String userId = null;
             String password = null;
             AuthenticationResult authenticated = null;
             for(Callback callback : callbacks)
             {
                 if (callback instanceof NameCallback)
                 {
-                    String id = ((NameCallback) callback).getDefaultName();
-                    try
-                    {
-                        name = getNameFromId(id);
-                    }
-                    catch (NamingException e)
-                    {
-                        _logger.warn("SASL Authentication Exception", e);
-                    }
+                    userId = ((NameCallback) callback).getDefaultName();
                     if(password != null)
                     {
-                        authenticated = doLDAPNameAuthentication(name, 
password);
+                        authenticated = getOrLoadAuthenticationResult(userId, 
password);
                     }
                 }
                 else if (callback instanceof PlainPasswordCallback)
                 {
                     password = 
((PlainPasswordCallback)callback).getPlainPassword();
-                    if(name != null)
+                    if (userId != null)
                     {
-                        authenticated = doLDAPNameAuthentication(name, 
password);
+                        authenticated = getOrLoadAuthenticationResult(userId, 
password);
                         if(authenticated.getStatus()== 
AuthenticationResult.AuthenticationStatus.SUCCESS)
                         {
                             
((PlainPasswordCallback)callback).setAuthenticated(true);

Modified: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProvider.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProvider.java?rev=1754010&r1=1754009&r2=1754010&view=diff
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProvider.java
 (original)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProvider.java
 Mon Jul 25 14:13:36 2016
@@ -22,16 +22,17 @@ package org.apache.qpid.server.security.
 import java.net.URI;
 import java.util.List;
 
-import org.apache.qpid.server.model.AuthenticationProvider;
 import org.apache.qpid.server.model.DerivedAttribute;
 import org.apache.qpid.server.model.ManagedAttribute;
 import org.apache.qpid.server.model.ManagedContextDefault;
 import org.apache.qpid.server.model.ManagedObject;
 import org.apache.qpid.server.model.TrustStore;
 import org.apache.qpid.server.security.auth.AuthenticationResult;
+import 
org.apache.qpid.server.security.auth.manager.CachingAuthenticationProvider;
 
 @ManagedObject( category = false, type = "OAuth2" )
-public interface OAuth2AuthenticationProvider<T extends 
OAuth2AuthenticationProvider<T>> extends AuthenticationProvider<T>
+public interface OAuth2AuthenticationProvider<T extends 
OAuth2AuthenticationProvider<T>>
+        extends CachingAuthenticationProvider<T>
 {
     String AUTHENTICATION_OAUTH2_CONNECT_TIMEOUT = 
"qpid.authentication.oauth2.connectTimeout";
     @ManagedContextDefault(name = AUTHENTICATION_OAUTH2_CONNECT_TIMEOUT)

Modified: 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImpl.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImpl.java?rev=1754010&r1=1754009&r2=1754010&view=diff
==============================================================================
--- 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImpl.java
 (original)
+++ 
qpid/java/trunk/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImpl.java
 Mon Jul 25 14:13:36 2016
@@ -34,6 +34,9 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 
 import javax.security.sasl.SaslException;
 import javax.security.sasl.SaslServer;
@@ -41,6 +44,8 @@ import javax.xml.bind.DatatypeConverter;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,6 +57,7 @@ import org.apache.qpid.server.model.Mana
 import org.apache.qpid.server.model.ManagedObjectFactoryConstructor;
 import org.apache.qpid.server.model.TrustStore;
 import org.apache.qpid.server.plugin.QpidServiceLoader;
+import org.apache.qpid.server.security.CryptoUtil;
 import org.apache.qpid.server.security.auth.AuthenticationResult;
 import 
org.apache.qpid.server.security.auth.manager.AbstractAuthenticationManager;
 import org.apache.qpid.server.util.ConnectionBuilder;
@@ -109,6 +115,7 @@ public class OAuth2AuthenticationProvide
     private int _connectTimeout;
     private int _readTimeout;
 
+    Cache<String, AuthenticationResult> _authenticationCache;
 
     @ManagedObjectFactoryConstructor
     protected OAuth2AuthenticationProviderImpl(final Map<String, Object> 
attributes,
@@ -129,6 +136,19 @@ public class OAuth2AuthenticationProvide
         _tlsCipherSuiteBlackList = getContextValue(List.class, 
ParameterizedTypes.LIST_OF_STRINGS, 
CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_BLACK_LIST);
         _connectTimeout = getContextValue(Integer.class, 
AUTHENTICATION_OAUTH2_CONNECT_TIMEOUT);
         _readTimeout = getContextValue(Integer.class, 
AUTHENTICATION_OAUTH2_READ_TIMEOUT);
+
+        Long cacheMaxSize = getContextValue(Long.class, 
AUTHORISATION_CACHE_MAX_SIZE);
+        Long cacheExpirationTime = getContextValue(Long.class, 
AUTHORISATION_CACHE_EXPIRATION_TIME);
+        if (cacheMaxSize == null || cacheMaxSize <= 0 || cacheExpirationTime 
== null || cacheExpirationTime <= 0)
+        {
+            LOGGER.debug("disabling authentication result caching");
+            cacheMaxSize = 0L;
+            cacheExpirationTime = 1L;
+        }
+        _authenticationCache = CacheBuilder.newBuilder()
+                                           .maximumSize(cacheMaxSize)
+                                           
.expireAfterWrite(cacheExpirationTime, TimeUnit.SECONDS)
+                                           .build();
     }
 
     @Override
@@ -339,18 +359,33 @@ public class OAuth2AuthenticationProvide
     }
 
     @Override
-    public AuthenticationResult authenticateViaAccessToken(String accessToken)
+    public AuthenticationResult authenticateViaAccessToken(final String 
accessToken)
     {
+        final String credentialDigest = CryptoUtil.sha256Hex(accessToken);
         try
         {
-            final Principal userPrincipal = 
_identityResolverService.getUserPrincipal(this, accessToken);
-            OAuth2UserPrincipal oauthUserPrincipal = new 
OAuth2UserPrincipal(userPrincipal.getName(), accessToken);
-            return new AuthenticationResult(oauthUserPrincipal);
+            return _authenticationCache.get(credentialDigest, new 
Callable<AuthenticationResult>()
+            {
+                @Override
+                public AuthenticationResult call()
+                {
+                    try
+                    {
+                        final Principal userPrincipal = 
_identityResolverService.getUserPrincipal(OAuth2AuthenticationProviderImpl.this,
 accessToken);
+                        OAuth2UserPrincipal oauthUserPrincipal = new 
OAuth2UserPrincipal(userPrincipal.getName(), accessToken);
+                        return new AuthenticationResult(oauthUserPrincipal);
+                    }
+                    catch (IOException | IdentityResolverException e)
+                    {
+                        LOGGER.error("Call to identity resolver failed", e);
+                        return new 
AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
+                    }
+                }
+            });
         }
-        catch (IOException | IdentityResolverException e)
+        catch (ExecutionException e)
         {
-            LOGGER.error("Call to identity resolver failed", e);
-            return new 
AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
+            throw new RuntimeException("Unexpected checked Exception while 
authenticating", e.getCause());
         }
     }
 

Modified: 
qpid/java/trunk/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImplTest.java
URL: 
http://svn.apache.org/viewvc/qpid/java/trunk/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImplTest.java?rev=1754010&r1=1754009&r2=1754010&view=diff
==============================================================================
--- 
qpid/java/trunk/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImplTest.java
 (original)
+++ 
qpid/java/trunk/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/oauth2/OAuth2AuthenticationProviderImplTest.java
 Mon Jul 25 14:13:36 2016
@@ -38,11 +38,11 @@ import javax.security.sasl.SaslServer;
 import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
 import org.apache.qpid.server.configuration.updater.TaskExecutor;
 import org.apache.qpid.server.model.Broker;
+import org.apache.qpid.server.model.BrokerTestHelper;
 import org.apache.qpid.server.model.ConfiguredObject;
 import org.apache.qpid.server.model.State;
 import org.apache.qpid.server.security.auth.AuthenticationResult;
 import 
org.apache.qpid.server.security.auth.manager.oauth2.cloudfoundry.CloudFoundryOAuth2IdentityResolverService;
-import org.apache.qpid.server.model.BrokerTestHelper;
 import org.apache.qpid.test.utils.QpidTestCase;
 
 public class OAuth2AuthenticationProviderImplTest extends QpidTestCase
@@ -226,6 +226,38 @@ public class OAuth2AuthenticationProvide
         assertFailure(authenticationResult, "invalid_token");
     }
 
+    public void testFailAuthenticateViaInvalidAccessTokenWithCache() throws 
Exception
+    {
+        OAuth2MockEndpoint mockIdentityResolverEndpoint = 
createMockIdentityResolverEndpoint();
+        
_server.setEndpoints(Collections.singletonMap(TEST_IDENTITY_RESOLVER_ENDPOINT_PATH,
+                                                      
mockIdentityResolverEndpoint));
+        mockIdentityResolverEndpoint.putExpectedParameter("token", 
TEST_INVALID_ACCESS_TOKEN);
+
+        // populate cache
+        mockIdentityResolverEndpoint.setResponse(400, 
"{\"error\":\"invalid_token\"}");
+        _authProvider.authenticateViaAccessToken(TEST_INVALID_ACCESS_TOKEN);
+
+        // hit cache
+        mockIdentityResolverEndpoint.setResponse(200, 
String.format("{\"user_name\":\"%s\"}", TEST_USER_NAME));
+        AuthenticationResult authenticationResult = 
_authProvider.authenticateViaAccessToken(TEST_INVALID_ACCESS_TOKEN);
+        assertFailure(authenticationResult, "invalid_token");
+    }
+
+    public void testAuthenticateViaAccessTokenWithCache() throws Exception
+    {
+        OAuth2MockEndpoint mockIdentityResolverEndpoint = 
createMockIdentityResolverEndpoint();
+        
_server.setEndpoints(Collections.singletonMap(TEST_IDENTITY_RESOLVER_ENDPOINT_PATH,
+                                                      
mockIdentityResolverEndpoint));
+
+        // populate cache
+        _authProvider.authenticateViaAccessToken(TEST_VALID_ACCESS_TOKEN);
+
+        // hit cache
+        mockIdentityResolverEndpoint.setResponse(500, "{\"error\":\"result 
should have been cached\"}");
+        AuthenticationResult authenticationResult = 
_authProvider.authenticateViaAccessToken(TEST_VALID_ACCESS_TOKEN);
+        assertSuccess(authenticationResult);
+    }
+
     private void assertSuccess(final AuthenticationResult authenticationResult)
     {
         assertEquals("Authentication was not successful: " + 
authenticationResult.getCause(),



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to