[jboss-cvs] JBossAS SVN: r67344 - in projects/security/security-jboss-sx/trunk: jbosssx/src/main/org/jboss/security/auth/callback and 3 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Wed Nov 21 12:23:11 EST 2007
Author: anil.saldhana at jboss.com
Date: 2007-11-21 12:23:11 -0500 (Wed, 21 Nov 2007)
New Revision: 67344
Added:
projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/
projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java
projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/SubjectActions.java
Removed:
projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/TestSecurityCache.java
Modified:
projects/security/security-jboss-sx/trunk/identity/
projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/auth/callback/AppCallbackHandler.java
projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/JBossAuthenticationManager.java
projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/JBossAuthenticationManagerUnitTestCase.java
projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/WebJASPIAuthMgrUnitTestCase.java
Log:
pull in the JaasSecurityManager codebase into a separate class
Property changes on: projects/security/security-jboss-sx/trunk/identity
___________________________________________________________________
Name: svn:ignore
+ target
Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/auth/callback/AppCallbackHandler.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/auth/callback/AppCallbackHandler.java 2007-11-21 17:04:46 UTC (rev 67343)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/auth/callback/AppCallbackHandler.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -24,6 +24,8 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.lang.reflect.Method;
+import java.security.Principal;
import java.util.Iterator;
import java.util.Map;
@@ -125,6 +127,12 @@
{
this.keyValuePair = mapOfValues;
}
+
+ public void setSecurityInfo(Principal p, Object cred)
+ {
+ this.username = p.getName();
+ this.credential = cred;
+ }
public String getPrompt()
{
@@ -169,6 +177,9 @@
if(this.consoleHandler)
pc.setPassword(getPasswordFromConsole(prompt));
else
+ if(this.credential != null && this.password == null)
+ pc.setPassword(this.getPassword());
+ else
pc.setPassword(password);
}
else if( c instanceof TextInputCallback )
@@ -242,5 +253,46 @@
}
return pwd.toCharArray();
}
+
+ /** Try to convert the credential value into a char[] using the
+ first of the following attempts which succeeds:
+
+ 1. Check for instanceof char[]
+ 2. Check for instanceof String and then use toCharArray()
+ 3. See if credential has a toCharArray() method and use it
+ 4. Use toString() followed by toCharArray().
+ @return a char[] representation of the credential.
+ */
+ private char[] getPassword()
+ {
+ char[] password = null;
+ if (credential instanceof char[])
+ {
+ password = (char[]) credential;
+ }
+ else if (credential instanceof String)
+ {
+ String s = (String) credential;
+ password = s.toCharArray();
+ }
+ else
+ {
+ try
+ {
+ Class[] types = {};
+ Method m = credential.getClass().getMethod("toCharArray", types);
+ Object[] args = {};
+ password = (char[]) m.invoke(credential, args);
+ }
+ catch (Exception e)
+ {
+ if (credential != null)
+ {
+ String s = credential.toString();
+ password = s.toCharArray();
+ }
+ }
+ }
+ return password;
+ }
}
-
Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/JBossAuthenticationManager.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/JBossAuthenticationManager.java 2007-11-21 17:04:46 UTC (rev 67343)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/JBossAuthenticationManager.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -21,30 +21,9 @@
*/
package org.jboss.security.plugins;
-import java.security.Principal;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.security.auth.message.AuthException;
-import javax.security.auth.message.AuthStatus;
-import javax.security.auth.message.MessageInfo;
-import javax.security.auth.message.config.AuthConfigFactory;
-import javax.security.auth.message.config.AuthConfigProvider;
-import javax.security.auth.message.config.ServerAuthConfig;
-import javax.security.auth.message.config.ServerAuthContext;
-import javax.security.jacc.PolicyContext;
-import org.jboss.logging.Logger;
-import org.jboss.security.AuthenticationManager;
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.auth.callback.AppCallbackHandler;
-import org.jboss.security.cache.JBossAuthenticationCache;
-import org.jboss.security.cache.SecurityCache;
-import org.jboss.security.cache.SecurityCacheException;
+import org.jboss.security.plugins.auth.JaasSecurityManagerBase;
//$Id$
@@ -54,195 +33,15 @@
* @since May 10, 2007
* @version $Revision$
*/
-public class JBossAuthenticationManager implements AuthenticationManager
-{
- private static Logger log = Logger.getLogger(JBossAuthenticationManager.class);
-
- protected String securityDomain = SecurityConstants.DEFAULT_APPLICATION_POLICY;
-
- protected CallbackHandler callbackHandler = null;
-
- private ThreadLocal<Subject> subjectLocal = new ThreadLocal<Subject>();
-
- private SecurityCache<Principal> sCache = null;
-
- private boolean cacheValidation = false;
-
- public JBossAuthenticationManager(String sdomain, CallbackHandler cbh)
+public class JBossAuthenticationManager extends JaasSecurityManagerBase
+{
+ public JBossAuthenticationManager()
{
- this.securityDomain = sdomain;
- this.callbackHandler = cbh;
- sCache = new JBossAuthenticationCache();
+ super();
}
-
- /**
- * Create JBossAuthenticationManager
- * @param sdomain SecurityDomain
- * @param cbh CallbackHandler
- * @param initCapacity Initial Capacity for the internal Security Cache
- * @param loadFactor Load Factor for the internal Security Cache
- * @param level Concurrency Level for the internal Security Cach
- */
- public JBossAuthenticationManager(String sdomain, CallbackHandler cbh,
- int initCapacity, float loadFactor, int level)
- {
- this.securityDomain = sdomain;
- this.callbackHandler = cbh;
- sCache = new JBossAuthenticationCache(initCapacity, loadFactor, level);
- }
-
- public void setSecurityCache(String className)
- {
- if(className == null)
- throw new IllegalArgumentException("className is null");
- ClassLoader cl = SubjectActions.getContextClassLoader();
- try
- {
- Class clazz = cl.loadClass(className);
- sCache = (SecurityCache<Principal>) clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
- }
- catch (Exception e)
- {
- throw new RuntimeException(e);
- }
- }
- /**
- * @see AuthenticationManager#getActiveSubject()
- */
- public Subject getActiveSubject()
- {
- return subjectLocal.get();
- }
-
- /**
- * @see AuthenticationManager#getSecurityDomain()
- */
- public String getSecurityDomain()
+ public JBossAuthenticationManager(String securityDomain, CallbackHandler handler)
{
- return securityDomain;
- }
-
- /**
- * @see AuthenticationManager#getTargetPrincipal(Principal, Map)
- */
- public Principal getTargetPrincipal(Principal principal, Map<String,Object> map)
- {
- throw new RuntimeException("Unimplemented");
- }
-
- /**
- * @see AuthenticationManager#isValid(Principal, Object)
- */
- public boolean isValid(Principal principal, Object credential)
- {
- return isValid(principal, credential, new Subject());
+ super(securityDomain, handler);
}
-
- /**
- * @see AuthenticationManager#isValid(Principal, Object, Subject)
- */
- public boolean isValid(Principal principal, Object credential, Subject subject)
- {
- if(subject == null)
- throw new IllegalArgumentException("Subject is null");
-
- HashMap<String,Object> map = new HashMap<String,Object>();
- if(sCache.cacheHit(principal))
- {
- Subject cacheSubject = validateCache(principal,credential,subject);
- if(cacheSubject != null)
- {
- subject = cacheSubject;
- subjectLocal.set(cacheSubject);
- return true;
- }
- }
- LoginContext lc = null;
-
- try
- {
- this.cacheValidation = false;
- lc = new LoginContext(securityDomain, subject, callbackHandler);
- lc.login();
-
- map.put(SecurityConstants.CREDENTIAL, credential);
- map.put(SecurityConstants.SUBJECT, subject);
- try
- {
- sCache.addCacheEntry(principal, map);
- }
- catch (SecurityCacheException e)
- {
- throw new RuntimeException(e);
- }
- subjectLocal.set(lc.getSubject());
- }
- catch (LoginException e)
- {
- log.trace("Login Failure:",e);
- return false;
- }
- return true;
- }
-
- /**
- * @see AuthenticationManager#isValid(MessageInfo, Subject, String)
- */
- public boolean isValid(MessageInfo requestMessage,Subject clientSubject, String layer)
- {
- AuthStatus status = AuthStatus.FAILURE;
-
- try
- {
- String contextID = PolicyContext.getContextID();
- AuthConfigFactory factory = AuthConfigFactory.getFactory();
- AuthConfigProvider provider = factory.getConfigProvider(layer,contextID,null);
- ServerAuthConfig serverConfig = provider.getServerAuthConfig(layer,contextID,
- new AppCallbackHandler("DUMMY","DUMMY".toCharArray()));
- ServerAuthContext sctx = serverConfig.getAuthContext(contextID,
- new Subject(), new HashMap());
- if(clientSubject == null)
- clientSubject = new Subject();
- Subject serviceSubject = new Subject();
- status = sctx.validateRequest(requestMessage, clientSubject, serviceSubject);
- this.subjectLocal.set(clientSubject);
- }
- catch(AuthException ae)
- {
- log.trace("AuthException:",ae);
- }
- return AuthStatus.SUCCESS == status ;
- }
-
- /**
- * Value added method for testing alone
- * @return
- */
- public boolean fromCache()
- {
- return cacheValidation ;
- }
-
- private Subject validateCache(Principal principal, Object credential, Subject subject)
- {
- this.cacheValidation = false;
- HashMap<String,Object> map = new HashMap<String,Object>();
- map.put(SecurityConstants.CREDENTIAL, credential);
- try
- {
- sCache.cacheOperation(principal, map);
- Object cacheReturn = sCache.get(principal);
- if(cacheReturn != null && cacheReturn instanceof Subject)
- {
- subject = (Subject) cacheReturn;
- this.cacheValidation = true;
- return subject;
- }
- }
- catch (SecurityCacheException e)
- {
- }
- return null;
- }
-}
+}
\ No newline at end of file
Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/JaasSecurityManagerBase.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -0,0 +1,767 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.plugins.auth;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.UndeclaredThrowableException;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.config.AuthConfigFactory;
+import javax.security.auth.message.config.AuthConfigProvider;
+import javax.security.auth.message.config.ServerAuthConfig;
+import javax.security.auth.message.config.ServerAuthContext;
+import javax.security.jacc.PolicyContext;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.AuthenticationManager;
+import org.jboss.security.AuthorizationManager;
+import org.jboss.security.RealmMapping;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityUtil;
+import org.jboss.security.SubjectSecurityManager;
+import org.jboss.security.auth.callback.AppCallbackHandler;
+import org.jboss.security.auth.callback.SecurityAssociationHandler;
+import org.jboss.security.plugins.SecurityContextAssociation;
+import org.jboss.util.CachePolicy;
+import org.jboss.util.TimedCachePolicy;
+
+/** The JaasSecurityManager is responsible both for authenticating credentials
+ associated with principals and for role mapping. This implementation relies
+ on the JAAS LoginContext/LoginModules associated with the security
+ domain name associated with the class for authentication,
+ and the context JAAS Subject object for role mapping.
+
+ @see #isValid(Principal, Object, Subject)
+ @see #getPrincipal(Principal)
+ @see #doesUserHaveRole(Principal, Set)
+
+ @author <a href="on at ibis.odessa.ua">Oleg Nitz</a>
+ @author Scott.Stark at jboss.org
+ @author Anil.Saldhana at jboss.org
+ @version $Revision: 62860 $
+*/
+public class JaasSecurityManagerBase
+ implements SubjectSecurityManager, RealmMapping
+{
+ /** The authentication cache object.
+ */
+ public static class DomainInfo implements TimedCachePolicy.TimedEntry
+ {
+ private static Logger log = Logger.getLogger(DomainInfo.class);
+ private static boolean trace = log.isTraceEnabled();
+ private LoginContext loginCtx;
+ private Subject subject;
+ private Object credential;
+ private Principal callerPrincipal;
+ private long expirationTime;
+ /** Is there an active authentication in process */
+ private boolean needsDestroy;
+ /** The number of users sharing this DomainInfo */
+ private int activeUsers;
+
+ /**
+ Create a cache entry with the given lifetime in seconds. Since this comes
+ from the TimedCachePolicy, its expected to be <= Integer.MAX_VALUE.
+
+ @param lifetime - lifetime in seconds. A lifetime <= 0 means no caching
+ with the exception of -1 which indicates that the cache entry never
+ expires.
+ */
+ public DomainInfo(long lifetime)
+ {
+ expirationTime = lifetime;
+ if( expirationTime != -1 )
+ expirationTime *= 1000;
+ }
+
+ synchronized int acquire()
+ {
+ return activeUsers ++;
+ }
+ synchronized int release()
+ {
+ int users = activeUsers --;
+ if( needsDestroy == true && users == 0 )
+ {
+ if( trace )
+ log.trace("needsDestroy is true, doing logout");
+ logout();
+ }
+ return users;
+ }
+ synchronized void logout()
+ {
+ if( trace )
+ log.trace("logout, subject="+subject+", this="+this);
+ try
+ {
+ if( loginCtx != null )
+ loginCtx.logout();
+ }
+ catch(Throwable e)
+ {
+ if( trace )
+ log.trace("Cache entry logout failed", e);
+ }
+ }
+
+ public void init(long now)
+ {
+ expirationTime += now;
+ }
+ public boolean isCurrent(long now)
+ {
+ boolean isCurrent = expirationTime == -1;
+ if( isCurrent == false )
+ isCurrent = expirationTime > now;
+ return isCurrent;
+ }
+ public boolean refresh()
+ {
+ return false;
+ }
+ /**
+ * This
+ */
+ public void destroy()
+ {
+ if( trace )
+ {
+ log.trace("destroy, subject="+subject+", this="+this
+ +", activeUsers="+activeUsers);
+ }
+
+ synchronized( this )
+ {
+ if( activeUsers == 0 )
+ logout();
+ else
+ {
+ if( trace )
+ log.trace("destroy saw activeUsers="+activeUsers);
+ needsDestroy = true;
+ }
+ }
+ }
+ public Object getValue()
+ {
+ return this;
+ }
+ public String toString()
+ {
+ StringBuffer tmp = new StringBuffer(super.toString());
+ tmp.append('[');
+ tmp.append(SubjectActions.toString(subject));
+ tmp.append(",credential.class=");
+ if( credential != null )
+ {
+ Class c = credential.getClass();
+ tmp.append(c.getName());
+ tmp.append('@');
+ tmp.append(System.identityHashCode(c));
+ }
+ else
+ {
+ tmp.append("null");
+ }
+ tmp.append(",expirationTime=");
+ tmp.append(expirationTime);
+ tmp.append(']');
+
+ return tmp.toString();
+ }
+ }
+
+ /** The name of the domain this instance is securing. It is used as
+ the appName into the SecurityPolicy.
+ */
+ private String securityDomain;
+ /** A cache of DomainInfo objects keyd by Principal. This is now
+ always set externally by our security manager service.
+ */
+ private CachePolicy domainCache;
+ /** The JAAS callback handler to use in defaultLogin */
+ private CallbackHandler handler;
+ /** The setSecurityInfo(Principal, Object) method of the handler obj */
+ private transient Method setSecurityInfo;
+ /** The flag to indicate that the Subject sets need to be deep copied*/
+ private boolean deepCopySubjectOption = false;
+
+ /** The log4j category for the security manager domain
+ */
+ protected Logger log;
+ protected boolean trace;
+
+ /** Creates a default JaasSecurityManager for with a securityDomain
+ name of 'other'.
+ */
+ public JaasSecurityManagerBase()
+ {
+ this("other", new SecurityAssociationHandler());
+ }
+ /** Creates a JaasSecurityManager for with a securityDomain
+ name of that given by the 'securityDomain' argument.
+ @param securityDomain the name of the security domain
+ @param handler the JAAS callback handler instance to use
+ @exception UndeclaredThrowableException thrown if handler does not
+ implement a setSecurityInfo(Princpal, Object) method
+ */
+ public JaasSecurityManagerBase(String securityDomain, CallbackHandler handler)
+ {
+ this.securityDomain = securityDomain;
+ this.handler = handler;
+ String categoryName = getClass().getName()+'.'+securityDomain;
+ this.log = Logger.getLogger(categoryName);
+ this.trace = log.isTraceEnabled();
+
+ // Get the setSecurityInfo(Principal principal, Object credential) method
+ Class[] sig = {Principal.class, Object.class};
+ try
+ {
+ setSecurityInfo = handler.getClass().getMethod("setSecurityInfo", sig);
+ }
+ catch (Exception e)
+ {
+ String msg = "Failed to find setSecurityInfo(Princpal, Object) method in handler";
+ throw new UndeclaredThrowableException(e, msg);
+ }
+ log.debug("CallbackHandler: "+handler);
+ }
+
+ /** The domainCache is typically a shared object that is populated
+ by the login code(LoginModule, etc.) and read by this class in the
+ isValid() method.
+ @see #isValid(Principal, Object, Subject)
+ */
+ public void setCachePolicy(CachePolicy domainCache)
+ {
+ this.domainCache = domainCache;
+ log.debug("CachePolicy set to: "+domainCache);
+ }
+
+ /**
+ * Flag to specify if deep copy of subject sets needs to be
+ * enabled
+ *
+ * @param flag
+ */
+ public void setDeepCopySubjectOption(Boolean flag)
+ {
+ log.debug("setDeepCopySubjectOption="+ flag);
+ this.deepCopySubjectOption = (flag == Boolean.TRUE) ;
+ }
+
+ /** Not really used anymore as the security manager service manages the
+ security domain authentication caches.
+ */
+ public void flushCache()
+ {
+ if( domainCache != null )
+ domainCache.flush();
+ }
+
+ /** Get the name of the security domain associated with this security mgr.
+ @return Name of the security manager security domain.
+ */
+ public String getSecurityDomain()
+ {
+ return securityDomain;
+ }
+
+ /** Get the currently authenticated Subject. This is a thread local
+ property shared across all JaasSecurityManager instances.
+ @return The Subject authenticated in the current thread if one
+ exists, null otherwise.
+ */
+ public Subject getActiveSubject()
+ {
+ /* This does not use SubjectActions.getActiveSubject since the caller
+ must have the correct permissions to access the
+ SecurityAssociation.getSubject method.
+ */
+ //return SecurityAssociation.getSubject();
+ Subject subj = null;
+ SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+ if(sc != null)
+ {
+ subj = sc.getUtil().getSubject();
+ }
+ return subj;
+ }
+
+ /** Validate that the given credential is correct for principal. This
+ returns the value from invoking isValid(principal, credential, null).
+ @param principal - the security domain principal attempting access
+ @param credential - the proof of identity offered by the principal
+ @return true if the principal was authenticated, false otherwise.
+ */
+ public boolean isValid(Principal principal, Object credential)
+ {
+ return isValid(principal, credential, null);
+ }
+
+ /** Validate that the given credential is correct for principal. This first
+ will check the current CachePolicy object if one exists to see if the
+ user's cached credentials match the given credential. If there is no
+ credential cache or the cache information is invalid or does not match,
+ the user is authenticated against the JAAS login modules configured for
+ the security domain.
+ @param principal - the security domain principal attempting access
+ @param credential the proof of identity offered by the principal
+ @param activeSubject - if not null, a Subject that will be populated with
+ the state of the authenticated Subject.
+ @return true if the principal was authenticated, false otherwise.
+ */
+ public boolean isValid(Principal principal, Object credential,
+ Subject activeSubject)
+ {
+ // Check the cache first
+ DomainInfo cacheInfo = getCacheInfo(principal, true);
+ if( trace )
+ log.trace("Begin isValid, principal:"+principal+", cache info: "+cacheInfo);
+
+ boolean isValid = false;
+ if( cacheInfo != null )
+ {
+ isValid = validateCache(cacheInfo, credential, activeSubject);
+ if( cacheInfo != null )
+ cacheInfo.release();
+ }
+ if( isValid == false )
+ isValid = authenticate(principal, credential, activeSubject);
+ if( trace )
+ log.trace("End isValid, "+isValid);
+ return isValid;
+ }
+
+ /**
+ * @see AuthenticationManager#isValid(MessageInfo, Subject, String)
+ */
+ public boolean isValid(MessageInfo requestMessage,Subject clientSubject, String layer)
+ {
+ AuthStatus status = AuthStatus.FAILURE;
+
+ try
+ {
+ String contextID = PolicyContext.getContextID();
+ AuthConfigFactory factory = AuthConfigFactory.getFactory();
+ AuthConfigProvider provider = factory.getConfigProvider(layer,contextID,null);
+ ServerAuthConfig serverConfig = provider.getServerAuthConfig(layer,contextID,
+ new AppCallbackHandler("DUMMY","DUMMY".toCharArray()));
+ ServerAuthContext sctx = serverConfig.getAuthContext(contextID,
+ new Subject(), new HashMap());
+ if(clientSubject == null)
+ clientSubject = new Subject();
+ Subject serviceSubject = new Subject();
+ status = sctx.validateRequest(requestMessage, clientSubject, serviceSubject);
+ //TODO: Add caching
+ }
+ catch(AuthException ae)
+ {
+ log.trace("AuthException:",ae);
+ }
+ return AuthStatus.SUCCESS == status ;
+ }
+
+ /** Map the argument principal from the deployment environment principal
+ to the developer environment. This is called by the EJB context
+ getCallerPrincipal() to return the Principal as described by
+ the EJB developer domain.
+ @return a Principal object that is valid in the deployment environment
+ if one exists. If no Subject exists or the Subject has no principals
+ then the argument principal is returned.
+ */
+ public Principal getPrincipal(Principal principal)
+ {
+ if(domainCache == null)
+ return principal;
+ Principal result = principal;
+ // Get the CallerPrincipal group member
+ synchronized( domainCache )
+ {
+ DomainInfo info = getCacheInfo(principal, false);
+ if( trace )
+ log.trace("getPrincipal, cache info: "+info);
+ if( info != null )
+ {
+ result = info.callerPrincipal;
+ // If the mapping did not have a callerPrincipal just use principal
+ if( result == null )
+ result = principal;
+ info.release();
+ }
+ }
+
+ return result;
+ }
+
+ /** Does the current Subject have a role(a Principal) that equates to one
+ of the role names. This method obtains the Group named 'Roles' from
+ the principal set of the currently authenticated Subject as determined
+ by the SecurityAssociation.getSubject() method and then creates a
+ SimplePrincipal for each name in roleNames. If the role is a member of the
+ Roles group, then the user has the role. This requires that the caller
+ establish the correct SecurityAssociation subject prior to calling this
+ method. In the past this was done as a side-effect of an isValid() call,
+ but this is no longer the case.
+
+ @param principal - ignored. The current authenticated Subject determines
+ the active user and assigned user roles.
+ @param rolePrincipals - a Set of Principals for the roles to check.
+
+ @see java.security.acl.Group;
+ @see Subject#getPrincipals()
+ */
+ public boolean doesUserHaveRole(Principal principal, Set<Principal> rolePrincipals)
+ {
+ AuthorizationManager am = SecurityUtil.getAuthorizationManager(securityDomain,
+ SecurityConstants.JAAS_CONTEXT_ROOT);
+ return am.doesUserHaveRole(principal, rolePrincipals);
+ }
+
+ /** Return the set of domain roles the current active Subject 'Roles' group
+ found in the subject Principals set.
+
+ @param principal - ignored. The current authenticated Subject determines
+ the active user and assigned user roles.
+ @return The Set<Principal> for the application domain roles that the
+ principal has been assigned.
+ */
+ public Set<Principal> getUserRoles(Principal principal)
+ {
+ AuthorizationManager am = SecurityUtil.getAuthorizationManager(securityDomain,
+ SecurityConstants.JAAS_CONTEXT_ROOT);
+ return am.getUserRoles(principal);
+ }
+
+ /**
+ * @see AuthenticationManager#getTargetPrincipal(Principal,Map)
+ */
+ public Principal getTargetPrincipal(Principal anotherDomainPrincipal,
+ Map<String,Object> contextMap)
+ {
+ throw new RuntimeException("Not implemented yet");
+ }
+
+ /** Currently this simply calls defaultLogin() to do a JAAS login using the
+ security domain name as the login module configuration name.
+
+ * @param principal - the user id to authenticate
+ * @param credential - an opaque credential.
+ * @return false on failure, true on success.
+ */
+ private boolean authenticate(Principal principal, Object credential,
+ Subject theSubject)
+ {
+ Subject subject = null;
+ boolean authenticated = false;
+ LoginException authException = null;
+
+ try
+ {
+ // Validate the principal using the login configuration for this domain
+ LoginContext lc = defaultLogin(principal, credential);
+ subject = lc.getSubject();
+
+ // Set the current subject if login was successful
+ if( subject != null )
+ {
+ // Copy the current subject into theSubject
+ if( theSubject != null )
+ {
+ SubjectActions.copySubject(subject, theSubject, false,this.deepCopySubjectOption);
+ }
+ else
+ {
+ theSubject = subject;
+ }
+
+ authenticated = true;
+ // Build the Subject based DomainInfo cache value
+ updateCache(lc, subject, principal, credential);
+ }
+ }
+ catch(LoginException e)
+ {
+ // Don't log anonymous user failures unless trace level logging is on
+ if( principal != null && principal.getName() != null || trace )
+ log.trace("Login failure", e);
+ authException = e;
+ }
+ // Set the security association thread context info exception
+ SubjectActions.setContextInfo("org.jboss.security.exception", authException);
+
+ return authenticated;
+ }
+
+ /** Pass the security info to the login modules configured for
+ this security domain using our SecurityAssociationHandler.
+ @return The authenticated Subject if successful.
+ @exception LoginException throw if login fails for any reason.
+ */
+ private LoginContext defaultLogin(Principal principal, Object credential)
+ throws LoginException
+ {
+ /* We use our internal CallbackHandler to provide the security info. A
+ copy must be made to ensure there is a unique handler per active
+ login since there can be multiple active logins.
+ */
+ Object[] securityInfo = {principal, credential};
+ CallbackHandler theHandler = null;
+ try
+ {
+ theHandler = (CallbackHandler) handler.getClass().newInstance();
+ setSecurityInfo.invoke(theHandler, securityInfo);
+ }
+ catch (Throwable e)
+ {
+ if( trace )
+ log.trace("Failed to create/setSecurityInfo on handler", e);
+ LoginException le = new LoginException("Failed to setSecurityInfo on handler");
+ le.initCause(e);
+ throw le;
+ }
+ Subject subject = new Subject();
+ LoginContext lc = null;
+ if( trace )
+ log.trace("defaultLogin, principal="+principal);
+ lc = SubjectActions.createLoginContext(securityDomain, subject, theHandler);
+ lc.login();
+ if( trace )
+ log.trace("defaultLogin, lc="+lc+", subject="+SubjectActions.toString(subject));
+ return lc;
+ }
+
+ /** Validate the cache credential value against the provided credential
+ */
+ private boolean validateCache(DomainInfo info, Object credential,
+ Subject theSubject)
+ {
+ if( trace )
+ {
+ StringBuffer tmp = new StringBuffer("Begin validateCache, info=");
+ tmp.append(info.toString());
+ tmp.append(";credential.class=");
+ if( credential != null )
+ {
+ Class c = credential.getClass();
+ tmp.append(c.getName());
+ tmp.append('@');
+ tmp.append(System.identityHashCode(c));
+ }
+ else
+ {
+ tmp.append("null");
+ }
+ log.trace(tmp.toString());
+ }
+
+ Object subjectCredential = info.credential;
+ boolean isValid = false;
+ // Check for a null credential as can be the case for an anonymous user
+ if( credential == null || subjectCredential == null )
+ {
+ // Both credentials must be null
+ isValid = (credential == null) && (subjectCredential == null);
+ }
+ // See if the credential is assignable to the cache value
+ else if( subjectCredential.getClass().isAssignableFrom(credential.getClass()) )
+ {
+ /* Validate the credential by trying Comparable, char[], byte[],
+ Object[], and finally Object.equals()
+ */
+ if( subjectCredential instanceof Comparable )
+ {
+ Comparable c = (Comparable) subjectCredential;
+ isValid = c.compareTo(credential) == 0;
+ }
+ else if( subjectCredential instanceof char[] )
+ {
+ char[] a1 = (char[]) subjectCredential;
+ char[] a2 = (char[]) credential;
+ isValid = Arrays.equals(a1, a2);
+ }
+ else if( subjectCredential instanceof byte[] )
+ {
+ byte[] a1 = (byte[]) subjectCredential;
+ byte[] a2 = (byte[]) credential;
+ isValid = Arrays.equals(a1, a2);
+ }
+ else if( subjectCredential.getClass().isArray() )
+ {
+ Object[] a1 = (Object[]) subjectCredential;
+ Object[] a2 = (Object[]) credential;
+ isValid = Arrays.equals(a1, a2);
+ }
+ else
+ {
+ isValid = subjectCredential.equals(credential);
+ }
+ }
+ else if( subjectCredential instanceof char[] && credential instanceof String )
+ {
+ char[] a1 = (char[]) subjectCredential;
+ char[] a2 = ((String) credential).toCharArray();
+ isValid = Arrays.equals(a1, a2);
+ }
+ else if( subjectCredential instanceof String && credential instanceof char[] )
+ {
+ char[] a1 = ((String) subjectCredential).toCharArray();
+ char[] a2 = (char[]) credential;
+ isValid = Arrays.equals(a1, a2);
+ }
+
+ // If the credentials match, set the thread's active Subject
+ if( isValid )
+ {
+ // Copy the current subject into theSubject
+ if( theSubject != null )
+ {
+ SubjectActions.copySubject(info.subject, theSubject, false,this.deepCopySubjectOption);
+ }
+ }
+ if( trace )
+ log.trace("End validateCache, isValid="+isValid);
+
+ return isValid;
+ }
+
+ /** An accessor method that synchronizes access on the domainCache
+ to avoid a race condition that can occur when the cache entry expires
+ in the presence of multi-threaded access. The allowRefresh flag should
+ be true for authentication accesses and false for other accesses.
+ Previously the other accesses included authorization and caller principal
+ mapping. Now the only use of the
+
+ @param principal - the caller identity whose cached credentials are to
+ be accessed.
+ @param allowRefresh - a flag indicating if the cache access should flush
+ any expired entries.
+ */
+ private DomainInfo getCacheInfo(Principal principal, boolean allowRefresh)
+ {
+ if( domainCache == null )
+ return null;
+
+ DomainInfo cacheInfo = null;
+ synchronized( domainCache )
+ {
+ if( allowRefresh == true )
+ cacheInfo = (DomainInfo) domainCache.get(principal);
+ else
+ cacheInfo = (DomainInfo) domainCache.peek(principal);
+ if( cacheInfo != null )
+ cacheInfo.acquire();
+ }
+ return cacheInfo;
+ }
+
+ private Subject updateCache(LoginContext lc, Subject subject,
+ Principal principal, Object credential)
+ {
+ // If we don't have a cache there is nothing to update
+ if( domainCache == null )
+ return subject;
+
+ long lifetime = 0;
+ if( domainCache instanceof TimedCachePolicy )
+ {
+ TimedCachePolicy cache = (TimedCachePolicy) domainCache;
+ lifetime = cache.getDefaultLifetime();
+ }
+ DomainInfo info = new DomainInfo(lifetime);
+ info.loginCtx = lc;
+ info.subject = new Subject();
+ SubjectActions.copySubject(subject, info.subject, true, this.deepCopySubjectOption);
+ info.credential = credential;
+
+ if( trace )
+ {
+ log.trace("updateCache, inputSubject="+SubjectActions.toString(subject)
+ +", cacheSubject="+SubjectActions.toString(info.subject));
+ }
+
+ /* Get the Subject callerPrincipal by looking for a Group called
+ 'CallerPrincipal'
+ */
+ Set subjectGroups = subject.getPrincipals(Group.class);
+ Iterator iter = subjectGroups.iterator();
+ while( iter.hasNext() )
+ {
+ Group grp = (Group) iter.next();
+ String name = grp.getName();
+ if( name.equals("CallerPrincipal") )
+ {
+ Enumeration members = grp.members();
+ if( members.hasMoreElements() )
+ info.callerPrincipal = (Principal) members.nextElement();
+ }
+ }
+
+ /* Handle null principals with no callerPrincipal. This is an indication
+ of an user that has not provided any authentication info, but
+ has been authenticated by the domain login module stack. Here we look
+ for the first non-Group Principal and use that.
+ */
+ if( principal == null && info.callerPrincipal == null )
+ {
+ Set subjectPrincipals = subject.getPrincipals(Principal.class);
+ iter = subjectPrincipals.iterator();
+ while( iter.hasNext() )
+ {
+ Principal p = (Principal) iter.next();
+ if( (p instanceof Group) == false )
+ info.callerPrincipal = p;
+ }
+ }
+
+ /* If the user already exists another login is active. Currently
+ only one is allowed so remove the old and insert the new. Synchronize
+ on the domainCache to ensure the removal and addition are an atomic
+ operation so that getCacheInfo cannot see stale data.
+ */
+ synchronized( domainCache )
+ {
+ if( domainCache.peek(principal) != null )
+ domainCache.remove(principal);
+ domainCache.insert(principal, info);
+ if( trace )
+ log.trace("Inserted cache info: "+info);
+ }
+ return info.subject;
+ }
+}
\ No newline at end of file
Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/SubjectActions.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/SubjectActions.java (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/org/jboss/security/plugins/auth/SubjectActions.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -0,0 +1,356 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.plugins.auth;
+
+import java.lang.reflect.Method;
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+import java.security.PrivilegedExceptionAction;
+import java.security.PrivilegedActionException;
+import java.security.Principal;
+import java.util.Set;
+import java.util.Iterator;
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.jacc.PolicyContext;
+import javax.security.jacc.PolicyContextException;
+
+import org.jboss.security.SecurityAssociation;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextFactory;
+import org.jboss.security.plugins.SecurityContextAssociation;
+
+/** Common PrivilegedAction used by classes in this package.
+ *
+ * @author Scott.Stark at jboss.org
+ * @author Anil.Saldhana at redhat.com
+ * @version $Revision: 65313 $
+ */
+class SubjectActions
+{
+ private static class ToStringSubjectAction implements PrivilegedAction
+ {
+ Subject subject;
+ ToStringSubjectAction(Subject subject)
+ {
+ this.subject = subject;
+ }
+ public Object run()
+ {
+ StringBuffer tmp = new StringBuffer();
+ tmp.append("Subject(");
+ tmp.append(System.identityHashCode(subject));
+ tmp.append(").principals=");
+ Iterator principals = subject.getPrincipals().iterator();
+ while( principals.hasNext() )
+ {
+ Object p = principals.next();
+ Class c = p.getClass();
+ tmp.append(c.getName());
+ tmp.append('@');
+ tmp.append(System.identityHashCode(c));
+ tmp.append('(');
+ tmp.append(p);
+ tmp.append(')');
+ }
+ return tmp.toString();
+ }
+ }
+
+ private static class GetSubjectAction implements PrivilegedExceptionAction
+ {
+ static PrivilegedExceptionAction ACTION = new GetSubjectAction();
+ public Object run() throws PolicyContextException
+ {
+ return (Subject) PolicyContext.getContext(SecurityConstants.SUBJECT_CONTEXT_KEY);
+ }
+ }
+
+ private static class CopySubjectAction implements PrivilegedAction
+ {
+ Subject fromSubject;
+ Subject toSubject;
+ boolean setReadOnly;
+ boolean deepCopy;
+
+ CopySubjectAction(Subject fromSubject, Subject toSubject, boolean setReadOnly)
+ {
+ this.fromSubject = fromSubject;
+ this.toSubject = toSubject;
+ this.setReadOnly = setReadOnly;
+ }
+ public void setDeepCopy(boolean flag)
+ {
+ this.deepCopy = flag;
+ }
+
+ public Object run()
+ {
+ Set principals = fromSubject.getPrincipals();
+ Set principals2 = toSubject.getPrincipals();
+ Iterator iter = principals.iterator();
+ while( iter.hasNext() )
+ principals2.add(getCloneIfNeeded(iter.next()));
+ Set privateCreds = fromSubject.getPrivateCredentials();
+ Set privateCreds2 = toSubject.getPrivateCredentials();
+ iter = privateCreds.iterator();
+ while( iter.hasNext() )
+ privateCreds2.add(getCloneIfNeeded(iter.next()));
+ Set publicCreds = fromSubject.getPublicCredentials();
+ Set publicCreds2 = toSubject.getPublicCredentials();
+ iter = publicCreds.iterator();
+ while( iter.hasNext() )
+ publicCreds2.add(getCloneIfNeeded(iter.next()));
+ if( setReadOnly == true )
+ toSubject.setReadOnly();
+ return null;
+ }
+
+ /** Check if the deepCopy flag is ON &&
+ * Object implements Cloneable and return cloned object */
+ private Object getCloneIfNeeded(Object obj)
+ {
+ Object clonedObject = null;
+ if(this.deepCopy && obj instanceof Cloneable)
+ {
+ Class clazz = obj.getClass();
+ try
+ {
+ Method cloneMethod = clazz.getMethod("clone", null);
+ clonedObject = cloneMethod.invoke(obj, null);
+ }
+ catch (Exception e)
+ {//Ignore non-cloneable issues
+ }
+ }
+ if(clonedObject == null)
+ clonedObject = obj;
+ return clonedObject;
+ }
+ }
+
+ private static class LoginContextAction implements PrivilegedExceptionAction
+ {
+ String securityDomain;
+ Subject subject;
+ CallbackHandler handler;
+ LoginContextAction(String securityDomain, Subject subject,
+ CallbackHandler handler)
+ {
+ this.securityDomain = securityDomain;
+ this.subject = subject;
+ this.handler = handler;
+ }
+ public Object run() throws Exception
+ {
+ LoginContext lc = new LoginContext(securityDomain, subject, handler);
+ return lc;
+ }
+ }
+
+ private static class GetTCLAction implements PrivilegedAction
+ {
+ static PrivilegedAction ACTION = new GetTCLAction();
+ public Object run()
+ {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ return loader;
+ }
+ }
+
+ private static class SetContextInfoAction implements PrivilegedAction
+ {
+ Object key;
+ Object value;
+ SetContextInfoAction(Object key, Object value)
+ {
+ this.key = key;
+ this.value = value;
+ }
+ public Object run()
+ {
+ //Set it on the current security context also
+ SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+ if(sc != null)
+ {
+ sc.getData().put(key.toString(), value);
+ }
+ return SecurityAssociation.setContextInfo(key, value);
+ }
+ }
+
+ interface PrincipalInfoAction
+ {
+ PrincipalInfoAction PRIVILEGED = new PrincipalInfoAction()
+ {
+ public void push(final Principal principal, final Object credential,
+ final Subject subject, final String securityDomain)
+ {
+ AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ public Object run()
+ {
+ //SecurityAssociation.pushSubjectContext(subject, principal, credential);
+ SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+ if(sc == null)
+ {
+ try
+ {
+ sc = SecurityContextFactory.createSecurityContext(principal, credential,
+ subject, securityDomain);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+ SecurityContextAssociation.setSecurityContext(sc);
+ return null;
+ }
+ }
+ );
+ }
+ public void pop()
+ {
+ AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ public Object run()
+ {
+ //SecurityAssociation.popSubjectContext();
+ SecurityContextAssociation.clearSecurityContext();
+ return null;
+ }
+ }
+ );
+ }
+ };
+
+ PrincipalInfoAction NON_PRIVILEGED = new PrincipalInfoAction()
+ {
+ public void push(Principal principal, Object credential, Subject subject,
+ String securityDomain)
+ {
+ //SecurityAssociation.pushSubjectContext(subject, principal, credential);
+ SecurityContext sc = SecurityContextAssociation.getSecurityContext();
+ if(sc == null)
+ {
+ try
+ {
+ sc = SecurityContextFactory.createSecurityContext(principal, credential,
+ subject, securityDomain);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+ else
+ {
+ sc.getUtil().createSubjectInfo(principal, credential, subject);
+ }
+ SecurityContextAssociation.setSecurityContext(sc);
+ }
+ public void pop()
+ {
+ //SecurityAssociation.popSubjectContext();
+ SecurityContextAssociation.clearSecurityContext();
+ }
+ };
+
+ void push(Principal principal, Object credential, Subject subject, String securityDomain);
+ void pop();
+ }
+
+ static Subject getActiveSubject() throws PrivilegedActionException
+ {
+ Subject subject = (Subject) AccessController.doPrivileged(GetSubjectAction.ACTION);
+ return subject;
+ }
+ static void copySubject(Subject fromSubject, Subject toSubject)
+ {
+ copySubject(fromSubject, toSubject, false);
+ }
+ static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly)
+ {
+ CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
+ if( System.getSecurityManager() != null )
+ AccessController.doPrivileged(action);
+ else
+ action.run();
+ }
+
+ static void copySubject(Subject fromSubject, Subject toSubject, boolean setReadOnly,
+ boolean deepCopy)
+ {
+ CopySubjectAction action = new CopySubjectAction(fromSubject, toSubject, setReadOnly);
+ action.setDeepCopy(deepCopy);
+ if( System.getSecurityManager() != null )
+ AccessController.doPrivileged(action);
+ else
+ action.run();
+ }
+
+ static LoginContext createLoginContext(String securityDomain, Subject subject,
+ CallbackHandler handler)
+ throws LoginException
+ {
+ LoginContextAction action = new LoginContextAction(securityDomain, subject, handler);
+ try
+ {
+ LoginContext lc = (LoginContext) AccessController.doPrivileged(action);
+ return lc;
+ }
+ catch(PrivilegedActionException e)
+ {
+ Exception ex = e.getException();
+ if( ex instanceof LoginException )
+ throw (LoginException) ex;
+ else
+ throw new LoginException(ex.getMessage());
+ }
+ }
+
+ static ClassLoader getContextClassLoader()
+ {
+ ClassLoader loader = (ClassLoader) AccessController.doPrivileged(GetTCLAction.ACTION);
+ return loader;
+ }
+
+ static Object setContextInfo(Object key, Object value)
+ {
+ SetContextInfoAction action = new SetContextInfoAction(key, value);
+ Object prevInfo = AccessController.doPrivileged(action);
+ return prevInfo;
+ }
+
+ static String toString(Subject subject)
+ {
+ ToStringSubjectAction action = new ToStringSubjectAction(subject);
+ String info = (String) AccessController.doPrivileged(action);
+ return info;
+ }
+}
\ No newline at end of file
Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/JBossAuthenticationManagerUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/JBossAuthenticationManagerUnitTestCase.java 2007-11-21 17:04:46 UTC (rev 67343)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/JBossAuthenticationManagerUnitTestCase.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -66,9 +66,6 @@
AppCallbackHandler acbh = new AppCallbackHandler("jduke","theduke".toCharArray());
AuthenticationManager am = new JBossAuthenticationManager("test",acbh);
assertTrue(am.isValid(p, "theduke"));
- assertNotNull("Subject is valid",am.getActiveSubject());
- assertTrue("Principal is present",
- am.getActiveSubject().getPrincipals().contains(p));
}
public void testUnsuccessfulLogin() throws Exception
@@ -79,51 +76,6 @@
assertFalse(am.isValid(p, "bad"));
}
- public void testSecurityCache() throws Exception
- {
- Principal p = new SimplePrincipal("jduke");
- AppCallbackHandler acbh = new AppCallbackHandler("jduke","theduke".toCharArray());
- JBossAuthenticationManager am = new JBossAuthenticationManager("test",acbh);
- assertFalse("Cache Validation is false", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertNotNull("Subject is valid",am.getActiveSubject());
- assertTrue("Principal is present",
- am.getActiveSubject().getPrincipals().contains(p));
- assertFalse("Cache Validation is false", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertTrue("Cache Validation", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertTrue("Cache Validation", am.fromCache());
-
- acbh = new AppCallbackHandler("jduke","dummy".toCharArray());
- am = new JBossAuthenticationManager("test",acbh);
- assertFalse(am.isValid(p, "dummy"));
- assertFalse("Cache Validation is false", am.fromCache());
- }
-
- public void testSecurityCacheInjection() throws Exception
- {
- Principal p = new SimplePrincipal("jduke");
- AppCallbackHandler acbh = new AppCallbackHandler("jduke","theduke".toCharArray());
- JBossAuthenticationManager am = new JBossAuthenticationManager("test",acbh);
- am.setSecurityCache(TestSecurityCache.class.getName());
- assertFalse("Cache Validation is false", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertNotNull("Subject is valid",am.getActiveSubject());
- assertTrue("Principal is present",
- am.getActiveSubject().getPrincipals().contains(p));
- assertFalse("Cache Validation is false", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertTrue("Cache Validation", am.fromCache());
- assertTrue(am.isValid(p, "theduke"));
- assertTrue("Cache Validation", am.fromCache());
-
- acbh = new AppCallbackHandler("jduke","dummy".toCharArray());
- am = new JBossAuthenticationManager("test",acbh);
- assertFalse(am.isValid(p, "dummy"));
- assertFalse("Cache Validation is false", am.fromCache());
- }
-
private void establishSecurityConfiguration()
{
SecurityActions.setJAASConfiguration((Configuration)new TestConfig());
Deleted: projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/TestSecurityCache.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/TestSecurityCache.java 2007-11-21 17:04:46 UTC (rev 67343)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/TestSecurityCache.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -1,82 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2007, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.test.authentication;
-
-import java.security.Principal;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.security.auth.Subject;
-
-import org.jboss.security.SecurityConstants;
-import org.jboss.security.cache.SecurityCache;
-import org.jboss.security.cache.SecurityCacheException;
-
-//$Id$
-
-/**
- * Test Security Cache
- * @author Anil.Saldhana at redhat.com
- * @since May 13, 2007
- * @version $Revision$
- */
-public class TestSecurityCache implements SecurityCache<Principal>
-{
- private ConcurrentHashMap<Principal, TestCacheEntry> map =
- new ConcurrentHashMap<Principal, TestCacheEntry>();
-
- public void addCacheEntry(Principal p, Map<String, Object> cmap)
- throws SecurityCacheException
- {
- TestCacheEntry tce = new TestCacheEntry();
- tce.cred = (String) cmap.get(SecurityConstants.CREDENTIAL);
- tce.subj = (Subject) cmap.get(SecurityConstants.SUBJECT);
- map.put(p, tce);
- }
-
- public boolean cacheHit(Principal p)
- {
- return map.containsKey(p);
- }
-
- public void cacheOperation(Principal p, Map<String, Object> cmap)
- throws SecurityCacheException
- {
- Object c = cmap.get(SecurityConstants.CREDENTIAL);
- String cred = (String)c;
- if(map.get(p).cred.equals(cred) == false)
- throw new SecurityCacheException("fail");
- }
-
- @SuppressWarnings("unchecked")
- public Subject get(Principal p) throws SecurityCacheException
- {
- return map.get(p).subj;
- }
-
- public class TestCacheEntry
- {
- public String cred;
- public Subject subj;
- }
-
-}
Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/WebJASPIAuthMgrUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/WebJASPIAuthMgrUnitTestCase.java 2007-11-21 17:04:46 UTC (rev 67343)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/tests/org/jboss/test/authentication/WebJASPIAuthMgrUnitTestCase.java 2007-11-21 17:23:11 UTC (rev 67344)
@@ -68,10 +68,7 @@
MessageInfo mi = new GenericMessageInfo(hsr, (HttpServletResponse)null);
Principal p = new SimplePrincipal("jduke");
AuthenticationManager am = new JBossAuthenticationManager(securityDomain,acbh);
- assertTrue(am.isValid(mi, null, "HTTP"));
- assertNotNull("Subject is valid",am.getActiveSubject());
- assertTrue("Principal is present",
- am.getActiveSubject().getPrincipals().contains(p));
+ assertTrue(am.isValid(mi, null, "HTTP"));
}
public void testUnsuccessfulLogin() throws Exception
@@ -80,18 +77,8 @@
MessageInfo mi = new GenericMessageInfo(hsr, (HttpServletResponse)null);
AuthenticationManager am = new JBossAuthenticationManager(securityDomain,acbh);
assertFalse(am.isValid(mi, null, "HTTP"));
- }
+ }
- public void testSecurityCache() throws Exception
- {
-
- }
-
- public void testSecurityCacheInjection() throws Exception
- {
-
- }
-
private void establishSecurityConfiguration()
{
XMLLoginConfigImpl xli = new XMLLoginConfigImpl();
@@ -109,4 +96,4 @@
hsr.getParameterMap().put("j_password", pass);
return hsr;
}
-}
+}
\ No newline at end of file
More information about the jboss-cvs-commits
mailing list