[jboss-cvs] JBossAS SVN: r73168 - trunk/tomcat/src/main/org/jboss/web/tomcat/security.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Thu May 8 15:06:53 EDT 2008


Author: anil.saldhana at jboss.com
Date: 2008-05-08 15:06:53 -0400 (Thu, 08 May 2008)
New Revision: 73168

Modified:
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/JBossSecurityMgrRealm.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/JaccAuthorizationRealm.java
Log:
JBAS-5514: deprecate legacy realms in favor of JBossWebRealm

Modified: trunk/tomcat/src/main/org/jboss/web/tomcat/security/JBossSecurityMgrRealm.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/JBossSecurityMgrRealm.java	2008-05-08 18:32:09 UTC (rev 73167)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/JBossSecurityMgrRealm.java	2008-05-08 19:06:53 UTC (rev 73168)
@@ -21,36 +21,6 @@
 */
 package org.jboss.web.tomcat.security;
 
-import java.security.Principal;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.HashSet;
-import java.io.IOException;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.security.auth.Subject;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.Realm;
-import org.apache.catalina.deploy.SecurityConstraint;
-import org.apache.catalina.deploy.LoginConfig;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.Response;
-import org.apache.catalina.realm.RealmBase;
-import org.apache.catalina.realm.Constants;
-import org.apache.catalina.realm.GenericPrincipal;
-import org.jboss.logging.Logger;
-import org.jboss.security.CertificatePrincipal;
-import org.jboss.security.RealmMapping;
-import org.jboss.security.SimplePrincipal;
-import org.jboss.security.SubjectSecurityManager;
-import org.jboss.security.auth.certs.SubjectDNMapping;
-import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler;
-
 /**
  * An implementation of the catelinz Realm and Valve interfaces. The Realm
  * implementation handles authentication and authorization using the JBossSX
@@ -62,6 +32,7 @@
  * so that web components may call EJBs and have the principal propagated. The
  * security association is removed when the request completes.
  *
+ * @deprecated User JBossWebRealm
  * @author Scott.Stark at jboss.org
  * @version $Revision$
  * @see org.jboss.security.AuthenticationManager
@@ -71,572 +42,6 @@
  * @see org.jboss.security.SecurityAssociation
  * @see org.jboss.security.SubjectSecurityManager
  */
-public class JBossSecurityMgrRealm extends RealmBase implements Realm
-{
-   static Logger log = Logger.getLogger(JBossSecurityMgrRealm.class);
-   /**
-    * The converter from X509 cert chain to Princpal
-    */
-   private CertificatePrincipal certMapping = new SubjectDNMapping();
-   /**
-    * The JBossSecurityMgrRealm category trace flag
-    */
-   private boolean trace;
-   /** The mode for handling the all roles mode of role-name=* */
-   private AllRolesMode allRolesMode = AllRolesMode.AUTH_ONLY_MODE;
-
-   /**
-    * Set the class name of the CertificatePrincipal used for mapping X509 cert
-    * chains to a Princpal.
-    *
-    * @param className the CertificatePrincipal implementation class that must
-    *                  have a no-arg ctor.
-    * @see org.jboss.security.CertificatePrincipal
-    */
-   public void setCertificatePrincipal(String className)
-   {
-      try
-      {
-         ClassLoader loader = Thread.currentThread().getContextClassLoader();
-         Class cpClass = loader.loadClass(className);
-         certMapping = (CertificatePrincipal) cpClass.newInstance();
-      }
-      catch (Exception e)
-      {
-         log.error("Failed to load CertificatePrincipal: " + className, e);
-         certMapping = new SubjectDNMapping();
-      }
-   }
-
-   protected Context getSecurityContext()
-   {
-      Context securityCtx = null;
-      // Get the JBoss security manager from the ENC context
-      try
-      {
-         InitialContext iniCtx = new InitialContext();
-         securityCtx = (Context) iniCtx.lookup("java:comp/env/security");
-      }
-      catch (NamingException e)
-      {
-         // Apparently there is no security context?
-      }
-      return securityCtx;
-   }
-
-   /**
-    * Override to allow a single realm to be shared as a realm and valve
-    */
-   public void start() throws LifecycleException
-   {
-      if (super.started == true)
-      {
-         return;
-      }
-      super.start();
-      trace = log.isTraceEnabled();
-   }
-
-   /**
-    * Override to allow a single realm to be shared as a realm and valve
-    */
-   public void stop() throws LifecycleException
-   {
-      if (super.started == false)
-      {
-         return;
-      }
-      super.stop();
-   }
-
-   public boolean hasResourcePermission(Request request, Response response,
-      SecurityConstraint[] constraints, org.apache.catalina.Context context)
-      throws IOException
-   {
-      if (constraints == null || constraints.length == 0)
-      {
-         return (true);
-      }
-
-      boolean hasPermission = false;
-      // Specifically allow access to the form login and form error pages
-      // and the "j_security_check" action
-      LoginConfig config = context.getLoginConfig();
-      if ((config != null) &&
-         (Constants.FORM_METHOD.equals(config.getAuthMethod())))
-      {
-         String requestURI = request.getRequestPathMB().toString();
-         String loginPage = config.getLoginPage();
-         if (loginPage.equals(requestURI))
-         {
-            if( trace )
-               log.trace("Allow access to login page " + loginPage);
-            return (true);
-         }
-         String errorPage = config.getErrorPage();
-         if (errorPage.equals(requestURI))
-         {
-            if( trace )
-               log.trace("Allow access to error page " + errorPage);
-            return (true);
-         }
-         if (requestURI.endsWith(Constants.FORM_ACTION))
-         {
-            if( trace )
-               log.trace("Allow access to username/password submission");
-            return (true);
-         }
-      }
-
-      // Which user principal have we already authenticated?
-      Principal principal = request.getPrincipal();
-      boolean denyfromall = false;
-      for (int i = 0; i < constraints.length; i++)
-      {
-         SecurityConstraint constraint = constraints[i];
-
-         String roles[];
-         if (constraint.getAllRoles())
-         {
-            // * means all roles defined in web.xml
-            roles = request.getContext().findSecurityRoles();
-         }
-         else
-         {
-            roles = constraint.findAuthRoles();
-         }
-
-         if (roles == null)
-         {
-            roles = new String[0];
-         }
-
-         if( trace )
-            log.trace("Checking roles " + principal);
-
-         if (roles.length == 0 && !constraint.getAllRoles())
-         {
-            if (constraint.getAuthConstraint())
-            {
-               if( trace )
-                  log.trace("No roles");
-               hasPermission = false; // No listed roles means no access at all
-               denyfromall = true;
-            }
-            else
-            {
-               if( trace )
-                  log.trace("Passing all access");
-               return (true);
-            }
-         }
-         else if (principal == null)
-         {
-            if( trace )
-               log.trace("No user authenticated, cannot grant access");
-            hasPermission = false;
-         }
-         else if (!denyfromall)
-         {
-            for (int j = 0; j < roles.length; j++)
-            {
-               if (hasRole(principal, roles[j]))
-               {
-                  hasPermission = true;
-               }
-               if( trace )
-                  log.trace("No role found:  " + roles[j]);
-            }
-         }
-      }
-
-      if (allRolesMode != AllRolesMode.STRICT_MODE
-         && hasPermission == false
-         && principal != null)
-      {
-         if (trace)
-         {
-            log.trace("Checking for all roles mode: " + allRolesMode);
-         }
-         // Check for an all roles(role-name="*")
-         for (int i = 0; i < constraints.length; i++)
-         {
-            SecurityConstraint constraint = constraints[i];
-            String roles[];
-            // If the all roles mode exists, sets
-            if (constraint.getAllRoles())
-            {
-               if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE)
-               {
-                  if (trace)
-                  {
-                     log.trace("Granting access for role-name=*, auth-only");
-                  }
-                  hasPermission = true;
-                  break;
-               }
-
-               // For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles
-               roles = request.getContext().findSecurityRoles();
-               if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE)
-               {
-                  if (trace)
-                  {
-                     log.trace("Granting access for role-name=*, strict auth-only");
-                  }
-                  hasPermission = true;
-                  break;
-               }
-            }
-         }
-      }
-
-      // Return a "Forbidden" message denying access to this resource
-      if (!hasPermission)
-      {
-         response.sendError
-            (HttpServletResponse.SC_FORBIDDEN,
-               sm.getString("realmBase.forbidden"));
-      }
-      return hasPermission;
-   }
-
-   /**
-    * Return the Principal associated with the specified chain of X509 client
-    * certificates.  If there is none, return <code>null</code>.
-    *
-    * @param certs Array of client certificates, with the first one in the array
-    *              being the certificate of the client itself.
-    */
-   public Principal authenticate(X509Certificate[] certs)
-   {
-      Principal principal = null;
-      Context securityCtx = getSecurityContext();
-      if (securityCtx == null)
-      {
-         if (trace)
-         {
-            log.trace("No security context for authenticate(X509Certificate[])");
-         }
-         return null;
-      }
-
-      try
-      {
-         // Get the JBoss security manager from the ENC context
-         SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
-         Subject subject = new Subject();
-         principal = certMapping.toPrinicipal(certs);
-         if (securityMgr.isValid(principal, certs, subject))
-         {
-            if (trace)
-            {
-               log.trace("User: " + principal + " is authenticated");
-            }
-            SecurityAssociationActions.setPrincipalInfo(principal, certs, subject);
-            // Get the CallerPrincipal mapping
-            RealmMapping realmMapping = (RealmMapping) securityCtx.lookup("realmMapping");
-            Principal oldPrincipal = principal;
-            principal = realmMapping.getPrincipal(oldPrincipal);
-            if (trace)
-            {
-               log.trace("Mapped from input principal: " + oldPrincipal
-                  + "to: " + principal);
-            }
-            // Get the caching principal
-            principal = getCachingPrincpal(realmMapping, oldPrincipal,
-               principal, certs, subject);
-         }
-         else
-         {
-            if (trace)
-            {
-               log.trace("User: " + principal + " is NOT authenticated");
-            }
-            principal = null;
-         }
-      }
-      catch (NamingException e)
-      {
-         log.error("Error during authenticate", e);
-      }
-      return principal;
-   }
-
-   /**
-    * Return the Principal associated with the specified username, which matches
-    * the digest calculated using the given parameters using the method
-    * described in RFC 2069; otherwise return <code>null</code>.
-    *
-    * @param username Username of the Principal to look up
-    * @param digest   Digest which has been submitted by the client
-    * @param nonce    Unique (or supposedly unique) token which has been used for
-    *                 this request
-    * @param nc       client nonce reuse count
-    * @param cnonce   client token
-    * @param qop      quality of protection
-    * @param realm    Realm name
-    * @param md5a2    Second MD5 digest used to calculate the digest : MD5(Method +
-    *                 ":" + uri)
-    */
-   public Principal authenticate(String username, String digest, String nonce,
-      String nc, String cnonce, String qop, String realm, String md5a2)
-   {
-      Principal principal = null;
-      Context securityCtx = getSecurityContext();
-      if (securityCtx == null)
-      {
-         if (trace)
-         {
-            log.trace("No security context for authenticate(String, String)");
-         }
-         return null;
-      }
-
-      Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
-      if (caller == null && username == null && digest == null)
-      {
-         return null;
-      }
-
-      try
-      {
-         DigestCallbackHandler handler = new DigestCallbackHandler(username, nonce,
-            nc, cnonce, qop, realm, md5a2);
-         CallbackHandlerPolicyContextHandler.setCallbackHandler(handler);
-
-         // Get the JBoss security manager from the ENC context
-         SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
-         principal = new SimplePrincipal(username);
-         Subject subject = new Subject();
-         if (securityMgr.isValid(principal, digest, subject))
-         {
-            log.trace("User: " + username + " is authenticated");
-            SecurityAssociationActions.setPrincipalInfo(principal, digest, subject);
-            // Get the CallerPrincipal mapping
-            RealmMapping realmMapping = (RealmMapping) securityCtx.lookup("realmMapping");
-            Principal oldPrincipal = principal;
-            principal = realmMapping.getPrincipal(oldPrincipal);
-            if (trace)
-            {
-               log.trace("Mapped from input principal: " + oldPrincipal
-                  + "to: " + principal);
-            }
-            // Get the caching principal
-            principal = getCachingPrincpal(realmMapping, oldPrincipal,
-               principal, digest, subject);
-         }
-         else
-         {
-            principal = null;
-            if (trace)
-            {
-               log.trace("User: " + username + " is NOT authenticated");
-            }
-         }
-      }
-      catch (NamingException e)
-      {
-         principal = null;
-         log.error("Error during authenticate", e);
-      }
-      finally
-      {
-         CallbackHandlerPolicyContextHandler.setCallbackHandler(null);
-      }
-      if (trace)
-      {
-         log.trace("End authenticate, principal=" + principal);
-      }
-      return principal;
-   }
-
-   /**
-    * Return the Principal associated with the specified username and
-    * credentials, if there is one; otherwise return <code>null</code>.
-    *
-    * @param username    Username of the Principal to look up
-    * @param credentials Password or other credentials to use in authenticating
-    *                    this username
-    */
-   public Principal authenticate(String username, String credentials)
-   {
-      if (trace)
-      {
-         log.trace("Begin authenticate, username=" + username);
-      }
-      Principal principal = null;
-      Context securityCtx = getSecurityContext();
-      if (securityCtx == null)
-      {
-         if (trace)
-         {
-            log.trace("No security context for authenticate(String, String)");
-         }
-         return null;
-      }
-
-      Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
-      if (caller == null && username == null && credentials == null)
-      {
-         return null;
-      }
-
-      try
-      {
-         // Get the JBoss security manager from the ENC context
-         SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
-         principal = new SimplePrincipal(username);
-         Subject subject = new Subject();
-         if (securityMgr.isValid(principal, credentials, subject))
-         {
-            log.trace("User: " + username + " is authenticated");
-            SecurityAssociationActions.setPrincipalInfo(principal, credentials, subject);
-            // Get the CallerPrincipal mapping
-            RealmMapping realmMapping = (RealmMapping) securityCtx.lookup("realmMapping");
-            Principal oldPrincipal = principal;
-            principal = realmMapping.getPrincipal(oldPrincipal);
-            if (trace)
-            {
-               log.trace("Mapped from input principal: " + oldPrincipal
-                  + "to: " + principal);
-            }
-            // Get the caching principal
-            principal = getCachingPrincpal(realmMapping, oldPrincipal,
-               principal, credentials, subject);
-         }
-         else
-         {
-            principal = null;
-            if (trace)
-            {
-               log.trace("User: " + username + " is NOT authenticated");
-            }
-         }
-      }
-      catch (NamingException e)
-      {
-         principal = null;
-         log.error("Error during authenticate", e);
-      }
-      if (trace)
-      {
-         log.trace("End authenticate, principal=" + principal);
-      }
-      return principal;
-   }
-
-   /**
-    * Returns <code>true</code> if the specified user <code>Principal</code> has
-    * the specified security role, within the context of this
-    * <code>Realm</code>; otherwise return <code>false</code>. This will be true
-    * when an associated role <code>Principal</code> can be found whose
-    * <code>getName</code> method returns a <code>String</code> equalling the
-    * specified role.
-    *
-    * @param principal <code>Principal</code> for whom the role is to be
-    *                  checked
-    * @param role      Security role to be checked
-    */
-   public boolean hasRole(Principal principal, String role)
-   {
-      return super.hasRole(principal, role); 
-   }
-
-   /**
-    * Return the Principal associated with the specified username and
-    * credentials, if there is one; otherwise return <code>null</code>.
-    *
-    * @param username    Username of the Principal to look up
-    * @param credentials Password or other credentials to use in authenticating
-    *                    this username
-    */
-   public Principal authenticate(String username, byte[] credentials)
-   {
-      return authenticate(username, new String(credentials));
-   }
-
-   /**
-    * Return a short name for this Realm implementation, for use in log
-    * messages.
-    */
-   protected String getName()
-   {
-      return getClass().getName();
-   }
-
-   /**
-    * Return the password associated with the given principal's user name.
-    */
-   protected String getPassword(String username)
-   {
-      String password = null;
-      return password;
-   }
-
-   /**
-    * Return the Principal associated with the given user name.
-    */
-   protected Principal getPrincipal(String username)
-   {
-      return new SimplePrincipal(username);
-   }
-
-   /**
-    * Access the set of role Princpals associated with the given caller princpal.
-    *
-    * @param principal - the Principal mapped from the authentication principal
-    *                  and visible from the HttpServletRequest.getUserPrincipal
-    * @return a possible null Set<Principal> for the caller roles
-    */
-   protected Set getPrincipalRoles(Principal principal)
-   {
-      if( (principal instanceof GenericPrincipal) == false )
-         throw new IllegalStateException("Expected GenericPrincipal, but saw: "+principal.getClass());
-      GenericPrincipal gp = (GenericPrincipal) principal;
-      String[] roleNames = gp.getRoles();
-      Set userRoles = new HashSet();
-      if( roleNames != null )
-      {
-         for(int n = 0; n < roleNames.length; n ++)
-         {
-            SimplePrincipal sp = new SimplePrincipal(roleNames[n]);
-            userRoles.add(sp);
-         }
-      }
-      return userRoles;
-   }
-
-   /**
-    * Create the session principal tomcat will cache to avoid callouts to this
-    * Realm.
-    *
-    * @param realmMapping    - the role mapping security manager
-    * @param authPrincipal   - the principal used for authentication and stored in
-    *                        the security manager cache
-    * @param callerPrincipal - the possibly different caller principal
-    *                        representation of the authenticated principal
-    * @param credential      - the credential used for authentication
-    * @return the tomcat session principal wrapper
-    */
-   protected Principal getCachingPrincpal(RealmMapping realmMapping,
-      Principal authPrincipal, Principal callerPrincipal, Object credential,
-      Subject subject)
-   {
-      // Cache the user roles in the principal
-      Set userRoles = realmMapping.getUserRoles(authPrincipal);
-      ArrayList roles = new ArrayList();
-      if (userRoles != null)
-      {
-         Iterator iterator = userRoles.iterator();
-         while (iterator.hasNext())
-         {
-            Principal role = (Principal) iterator.next();
-            roles.add(role.getName());
-         }
-      }
-      JBossGenericPrincipal gp = new JBossGenericPrincipal(this, subject,
-         authPrincipal, callerPrincipal, credential, roles, userRoles);
-      return gp;
-   }
+public class JBossSecurityMgrRealm extends JBossWebRealm
+{ 
 }

Modified: trunk/tomcat/src/main/org/jboss/web/tomcat/security/JaccAuthorizationRealm.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/JaccAuthorizationRealm.java	2008-05-08 18:32:09 UTC (rev 73167)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/JaccAuthorizationRealm.java	2008-05-08 19:06:53 UTC (rev 73168)
@@ -21,395 +21,16 @@
 */
 package org.jboss.web.tomcat.security;
 
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.security.Principal;
-import java.security.Permission;
-import java.security.ProtectionDomain;
-import java.security.Policy;
-import java.security.CodeSource;
-import java.util.Set;
-import java.util.List;
 
-import javax.security.jacc.WebUserDataPermission;
-import javax.security.jacc.PolicyContext;
-import javax.security.jacc.WebResourcePermission;
-import javax.security.jacc.WebRoleRefPermission;
-import javax.security.jacc.PolicyContextException;
-import javax.security.auth.Subject;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.catalina.Context;
-import org.apache.catalina.Wrapper;
-import org.apache.catalina.connector.Request;
-import org.apache.catalina.connector.Response;
-import org.apache.catalina.deploy.SecurityConstraint;
-import org.jboss.logging.Logger;
-import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData;
-import org.jboss.metadata.javaee.spec.SecurityRoleRefsMetaData;
-import org.jboss.metadata.web.jboss.JBossWebMetaData;
-import org.jboss.security.SubjectSecurityManager;
-
 /** A subclass of JBossSecurityMgrRealm that peforms authorization based on
  * the JACC permissions and active Policy implementation.
  * 
+ * @deprecated Use JBossWebRealm
+ * 
  * @author Scott.Stark at jboss.org
  * @author Anil.Saldhana at jboss.org
  * @version $Revision$
  */
-public class JaccAuthorizationRealm extends JBossSecurityMgrRealm
-{
-   static Logger log = Logger.getLogger(JaccAuthorizationRealm.class);
-
-   /** The JACC PolicyContext key for the current Subject */
-   private static final String SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container";
-   /** The current servlet request */
-   private static ThreadLocal activeRequest = new ThreadLocal();
-   private boolean trace;
-   private Policy policy;
-
-   /**
-    * JBAS-2519:Delegate to JACC provider for unsecured resources in web.xml 
-    */
-   private boolean unprotectedResourceDelegation = false;
-   private String securityConstraintProviderClass = "";
-
-   public JaccAuthorizationRealm()
-   {
-      policy = Policy.getPolicy();
-      trace = log.isTraceEnabled();
-   }
-
-   public boolean hasResourcePermission(Request request, Response response,
-      SecurityConstraint[] securityConstraints, Context context)
-      throws IOException
-   {
-      Wrapper servlet = request.getWrapper();
-      if (servlet != null)
-      {
-         activeRequest.set(getServletName(servlet));
-      }
-      Principal requestPrincipal = request.getPrincipal();
-      HttpServletRequest httpRequest = request.getRequest();
-      String uri = requestURI(request);
-      WebResourcePermission perm = new WebResourcePermission(uri, httpRequest.getMethod());
-      boolean allowed = checkSecurityAssociation(perm, requestPrincipal);
-      if( trace )
-         log.trace("hasResourcePermission, perm="+perm+", allowed="+allowed);
-      if( allowed == false )
-      {
-         response.sendError(HttpServletResponse.SC_FORBIDDEN,
-            sm.getString("realmBase.forbidden"));
-      }
-      return allowed;
-   }
-
-   public boolean hasRole(Principal principal, String name)
-   {
-      // 
-      String servletName = (String) activeRequest.get();
-      JBossWebMetaData metaData = SecurityAssociationValve.activeWebMetaData.get();
-      SecurityRoleRefsMetaData roleRefs = metaData.getSecurityRoleRefs(servletName);
-      String roleName = name;
-      if (roleRefs != null)
-      {
-         for(SecurityRoleRefMetaData ref : roleRefs)
-         {
-            if( ref.getRoleLink().equals(name) )
-            {
-               roleName = ref.getName();
-               break;
-            }
-         }
-      }
-      
-      WebRoleRefPermission perm = new WebRoleRefPermission(servletName, roleName);
-      Principal[] principals = {principal};
-      Set roles = getPrincipalRoles(principal);
-      if( roles != null )
-      {
-         principals = new Principal[roles.size()];
-         roles.toArray(principals);
-      }
-      boolean allowed = checkSecurityAssociation(perm, principals);
-      if( trace )
-         log.trace("hasRole, perm="+perm+", allowed="+allowed);
-      return allowed;
-   }
-
-   public boolean hasUserDataPermission(Request request, Response response,
-      SecurityConstraint[] constraints) throws IOException
-   {
-      HttpServletRequest httpRequest = request.getRequest();
-      Principal requestPrincpal = request.getPrincipal();
-      establishSubjectContext(requestPrincpal);
-      String uri = requestURI(request);
-      WebUserDataPermission perm = new WebUserDataPermission(uri, httpRequest.getMethod());
-      if( trace )
-         log.trace("hasUserDataPermission, p="+perm);
-      boolean ok = false;
-      try
-      {
-         Principal[] principals = null;
-         ok = checkSecurityAssociation(perm, principals);
-      }
-      catch(Exception e)
-      {
-         if( trace )
-            log.trace("Failed to checkSecurityAssociation", e);
-      }
-
-      /* If the constraint is not valid delegate to super to redirect to the
-      ssl port if allowed
-      */
-      if( ok == false )
-         ok = super.hasUserDataPermission(request, response, constraints);
-      return ok;
-   }
-
-   /** 
-    * Get the Security Constraints Provider Class
-    * @return
-    */
-   public String getSecurityConstraintProviderClass()
-   {
-      return securityConstraintProviderClass;
-   }
-
-   /**
-    * Set the Security Constraints Provider Class 
-    * @param securityConstraintProviderClass
-    */
-   public void setSecurityConstraintProviderClass(String securityConstraintProviderClass)
-   {
-      this.securityConstraintProviderClass = securityConstraintProviderClass;
-   }
-
-   /**
-    * Whether the delegation to JACC provider
-    * for unprotected resources is enabled
-    * 
-    * @return
-    */
-   public boolean isUnprotectedResourceDelegation()
-   {
-      return unprotectedResourceDelegation;
-   }
-
-   /**
-    * Set whether the delegation to JACC provider
-    * for unprotected resources must be enabled
-    * 
-    * @param unprotectedResourceDelegation
-    */
-   public void setUnprotectedResourceDelegation(boolean unprotectedResourceDelegation)
-   {
-      this.unprotectedResourceDelegation = unprotectedResourceDelegation;
-   }  
-   
-   /**
-    * JBAS-2519:Delegate to JACC provider for unsecured resources in web.xml
-    */
-   public SecurityConstraint[] findSecurityConstraints(Request request, Context context)
-   {  
-      SecurityConstraint[] scarr = super.findSecurityConstraints(request, context);
-      if( (scarr == null || scarr.length == 0) 
-            && this.unprotectedResourceDelegation)
-      {
-         scarr = getSecurityConstraintsFromProvider(request, context);
-      }
-      return scarr;
-   }
-
-   /** See if the given JACC permission is implied using the caller as
-    * obtained from either the
-    * PolicyContext.getContext(javax.security.auth.Subject.container) or
-    * the info associated with the requestPrincipal.
-    * 
-    * @param perm - the JACC permission to check
-    * @param requestPrincpal - the http request getPrincipal
-    * @return true if the permission is allowed, false otherwise
-    */ 
-   private boolean checkSecurityAssociation(Permission perm, Principal requestPrincpal)
-   {
-      // Get the caller
-      Subject caller = establishSubjectContext(requestPrincpal);
-
-      // Get the caller principals, its null if there is no caller
-      Principal[] principals = null;
-      if( caller != null )
-      {
-         if( trace )
-            log.trace("No active subject found, using ");
-         Set principalsSet = caller.getPrincipals();
-         principals = new Principal[principalsSet.size()];
-         principalsSet.toArray(principals);
-      }
-      return checkSecurityAssociation(perm, principals);
-   }
-   /** See if the given permission is implied by the Policy. This calls
-    * Policy.implies(pd, perm) with the ProtectionDomain built from the
-    * active CodeSource set by the JaccContextValve, and the given
-    * principals.
-    * 
-    * @param perm - the JACC permission to evaluate
-    * @param principals - the possibly null set of principals for the caller
-    * @return true if the permission is allowed, false otherwise
-    */ 
-   private boolean checkSecurityAssociation(Permission perm, Principal[] principals)
-   {
-      CodeSource webCS = (CodeSource) JaccContextValve.activeCS.get();
-      ProtectionDomain pd = new ProtectionDomain(webCS, null, null, principals);
-      boolean allowed = policy.implies(pd, perm);
-      if( trace )
-      {
-         String msg = (allowed ? "Allowed: " : "Denied: ") +perm;
-         log.trace(msg);
-      }
-      return allowed;
-   }
-
-   /**
-    * Ensure that the JACC PolicyContext Subject handler has access to the
-    * authenticated Subject. The caching of the authentication state by tomcat
-    * means that we need to retrieve the Subject from the JBossGenericPrincipal
-    * if the realm was not invoked to authenticate the caller.
-    * 
-    * @param principal - the http request getPrincipal
-    * @return the authenticated Subject is there is one, null otherwise
-    */ 
-   private Subject establishSubjectContext(Principal principal)
-   {
-      Subject caller = null;
-      try
-      {
-         caller = (Subject) PolicyContext.getContext(SUBJECT_CONTEXT_KEY);
-      }
-      catch (PolicyContextException e)
-      {
-         if( trace )
-            log.trace("Failed to get subject from PolicyContext", e);
-      }
-
-      if( caller == null )
-      {
-         // Test the request principal that may come from the session cache 
-         if( principal instanceof JBossGenericPrincipal )
-         {
-            JBossGenericPrincipal jgp = (JBossGenericPrincipal) principal;
-            caller = jgp.getSubject();
-            // 
-            if (trace)
-               log.trace("Restoring principal info from cache"); 
-            SecurityAssociationActions.setPrincipalInfo(jgp.getAuthPrincipal(),
-               jgp.getCredentials(), jgp.getSubject());
-         }
-      }
-      return caller;
-   }
-   
-   /**
-    * Jacc Specification : Appendix
-    *  B.19 Calling isUserInRole from JSP not mapped to a Servlet
-    *  Checking a WebRoleRefPermission requires the name of a Servlet to
-    *  identify the scope of the reference to role translation. The name of a 
-    *  scoping  servlet has not been established for an unmapped JSP.
-    *  
-    *  Resolution- For every security role in the web application add a
-    *  WebRoleRefPermission to the corresponding role. The name of all such
-    *  permissions shall be the empty string, and the actions of each
-    *  permission shall be the corresponding role name. 
-    *  When checking a WebRoleRefPermission from a JSP not mapped to a servlet, 
-    *  use a permission with the empty string as its name and with the argument to is
-    *  UserInRole as its actions.  
-    * 
-    * @param servlet Wrapper
-    * @return empty string if it is for an unmapped jsp or name of the servlet for others 
-    */
-   private String getServletName(Wrapper servlet)
-   {  
-      //For jsp, the mapping will be (*.jsp, *.jspx)
-      String[] mappings = servlet.findMappings();
-      if(trace)
-         log.trace("[getServletName:servletmappings="+mappings +
-               ":servlet.getName()="+servlet.getName()+"]");
-      if("jsp".equals(servlet.getName())
-            && (mappings != null && mappings[0].indexOf("*.jsp")> -1))
-      return "";
-      else
-         return servlet.getName();
-   }
-   
-   /**
-    * Get a set of SecurityConstraints from either the PolicyProvider
-    * or the securityConstraintProviderClass class, via reflection
-    * 
-    * @param request
-    * @param context 
-    * @return an array of SecurityConstraints
-    */
-   private SecurityConstraint[] getSecurityConstraintsFromProvider(Request request, Context context)
-   { 
-      SecurityConstraint[] scarr = null;
-      Class[] sig = {Request.class, Context.class};
-      Object[] args = {request, context};
-      
-      Method findsc = null;
-      
-      //Try the Policy Provider 
-      try
-      {
-         findsc = policy.getClass().getMethod("findSecurityConstraints", sig);
-         scarr = (SecurityConstraint[])findsc.invoke(policy, args);
-      }catch(Throwable t)
-      {
-         if(trace)
-            log.error("Error obtaining security constraints from policy",t);
+public class JaccAuthorizationRealm extends JBossWebRealm
+{   
 }
-      //If the policy provider did not provide the security constraints
-      //check if a seperate SC provider is plugged in
-      if(scarr == null || scarr.length == 0)
-      {
-         if(securityConstraintProviderClass == "" ||
-               securityConstraintProviderClass.length() == 0)
-         {
-            if(trace)
-               log.trace("unprotectedResourceDelegation is true "+
-               "but securityConstraintProviderClass is empty");
-         }
-         else
-            //Try to call the method on the provider class
-            try
-         {
-               Class clazz = Thread.currentThread().getContextClassLoader().loadClass(securityConstraintProviderClass);
-               Object obj = clazz.newInstance(); 
-               findsc = clazz.getMethod("findSecurityConstraints", sig); 
-               if(trace)
-                  log.trace("findSecurityConstraints method found in securityConstraintProviderClass");
-               scarr = (SecurityConstraint[])findsc.invoke(obj, args);
-         }
-         catch (Throwable t)
-         {
-            log.error("Error instantiating "+securityConstraintProviderClass,t);
-         }   
-      } 
-      return scarr;
-   }
-
-   /**
-    * Get the canonical request uri from the request mapping data requestPath
-    * @param request
-    * @return the request URI path
-    */
-   static String requestURI(Request request)
-   {
-      String uri = request.getMappingData().requestPath.getString();
-      if( uri == null || uri.equals("/") )
-      {
-         uri = "";
-      }
-      return uri;
-   }
-   
-}




More information about the jboss-cvs-commits mailing list