Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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;
  
 import static org.jboss.security.SecurityConstants.ROLES_IDENTIFIER;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 
 //$Id: JBossAuthorizationManager.java 78790 2008-09-23 15:45:14Z anil.saldhana@jboss.com $
 
Authorization Manager implementation

Author(s):
Anil Saldhana
Version:
$Revision: 78790 $
Since:
Jan 3, 2006
 
 public class JBossAuthorizationManager 
 implements AuthorizationManager 
 {  
    private String securityDomain;  
    
    private static Logger log = Logger.getLogger(JBossAuthorizationManager.class);
    
    protected boolean trace = .isTraceEnabled(); 
    
    private AuthorizationContext authorizationContext = null;
    
    //Lock deals with synchronization of authorizationContext usage
    private Lock lock = new ReentrantLock();
    
    public JBossAuthorizationManager(String securityDomainName)
    {
       this. = securityDomainName;
    } 
   
   
 
    public int authorize(Resource resourcethrows AuthorizationException
    {
      validateResource(resource);
      Subject subject = SubjectActions.getActiveSubject();
      return internalAuthorization(resource,subjectnull);
   }
   
   
   public int authorize(Resource resourceSubject subject)
   {
      return internalAuthorization(resourcesubjectnull);
   }
   
   
   public int authorize(Resource resourceSubject subject,
         RoleGroup rolethrows AuthorizationException
   {
      this.validateResource(resource);
      return internalAuthorization(resourcesubjectrole);
   }

   
   public int authorize(Resource resourceSubject subject
         Group roleGroupthrows AuthorizationException
   { 
      this.validateResource(resource);
      return internalAuthorization(resourcesubjectgetRoleGroup(roleGroup));
   }
   

   
   public <T> EntitlementHolder<T> getEntitlements(Class<T> clazz,
         Resource resourceIdentity identity)
   { 
      ACLContext aclContext = new JBossACLContext(this.);
      return aclContext.getEntitlements(clazzresourceidentity);
   }

   
   
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.

Parameters:
principal - ignored. The current authenticated Subject determines the active user and assigned user roles.
rolePrincipals - a Set of Principals for the roles to check.
See also:
java.security.acl.Group;
javax.security.auth.Subject.getPrincipals()
   public boolean doesUserHaveRole(Principal principalSet<PrincipalrolePrincipals)
   {
      boolean hasRole = false;
      RoleGroup roles = this.getCurrentRoles(principal);
      if )
         .trace("doesUserHaveRole(Set), roles: "+roles);
      if(roles != null)
      {
         Iterator<Principaliter = rolePrincipals.iterator();
         whilehasRole == false && iter.hasNext() )
         {
            Principal role = (Principaliter.next();
            hasRole = doesRoleGroupHaveRole(roleroles);
            if )
               .trace("hasRole("+role+")="+hasRole);
         }
         if )
            .trace("hasRole="+hasRole);
      } 
      return hasRole;
   }
   
   
Does the current Subject have a role(a Principal) that equates to one of the role names.

Parameters:
principal - ignored. The current authenticated Subject determines the active user and assigned user roles.
role - the application domain role that the principal is to be validated against.
Returns:
true if the active principal has the role, false otherwise.
See also:
doesUserHaveRole(java.security.Principal,java.util.Set)
   public boolean doesUserHaveRole(Principal principalPrincipal role)
   {
      boolean hasRole = false;
      RoleGroup roles = this.getCurrentRoles(principal);
      hasRole = doesRoleGroupHaveRole(roleroles); 
      return hasRole;
   } 
   
   
Return the set of domain roles the current active Subject 'Roles' group found in the subject Principals set.

Parameters:
principal - ignored. The current authenticated Subject determines the active user and assigned user roles.
Returns:
The Set<Principal> for the application domain roles that the principal has been assigned.
   public Set<PrincipalgetUserRoles(Principal principal)
   { 
      RoleGroup userRoles = getCurrentRoles(principal);
      return this.getRolesAsSet(userRoles); 
   }  
     
   
   
Check that the indicated application domain role is a member of the user's assigned roles. This handles the special AnybodyPrincipal and NobodyPrincipal independent of the Group implementation.

Parameters:
role , the application domain role required for access
userRoles , the set of roles assigned to the user
Returns:
true if role is in userRoles or an AnybodyPrincipal instance, false if role is a NobodyPrincipal or no a member of userRoles
   protected boolean doesRoleGroupHaveRole(Principal roleRoleGroup userRoles)
   {
      // First check that role is not a NobodyPrincipal
      if (role instanceof NobodyPrincipal)
         return false;
      
      // Check for inclusion in the user's role set
      boolean isMember = userRoles.containsRole(new SimpleRole(role.getName())); 
      if (isMember == false)
      {   // Check the AnybodyPrincipal special cases
         isMember = (role instanceof AnybodyPrincipal);
      }
      
      return isMember;
   } 
   
   public String toString()
   {
      StringBuffer buf = new StringBuffer();
      buf.append("[AuthorizationManager:class=").append(getClass().getName());
      buf.append(":").append(this.).append(":");
      buf.append("]");
      return buf.toString();
   } 
   
   //Value added methods
   
Set the AuthorizationContext
   {
      if(ac == null)
         throw new IllegalArgumentException("AuthorizationContext is null");
      .lock();
      try
      {  
         String sc = ac.getSecurityDomain();
         if(this..equals(sc) == false)
            throw new IllegalArgumentException("The Security Domain "sc 
                  + " does not match with " + this.);
         this. = ac;  
      }
      finally
      {
         .unlock();
      }
   }
   
   public String getSecurityDomain()
   {
      return this.;
   }
   

   
   public Group getTargetRoles(Principal targetPrincipalMap<String,ObjectcontextMap)
   {
      throw new NotImplementedException();
   }
   //Private Methods
   private HashSet<PrincipalgetRolesAsSet(RoleGroup roles)
   {
      HashSet<PrincipaluserRoles = null;
      ifroles != null )
      {
         userRoles = new HashSet<Principal>();
         List<RolerolesList = roles.getRoles();
         for(Role rrolesList)
         {
            userRoles.add(new SimplePrincipal(r.getRoleName()));
         } 
      }
      return userRoles;
   } 

   
   public RoleGroup getSubjectRoles(Subject authenticatedSubjectCallbackHandler cbh)
   {
      if(authenticatedSubject == null)
         return null;
      
      //Ask the CBH for the SecurityContext
      try
      {
         cbh.handle(new Callback[]{scb});
      }
      catch (Exception e)
      {
         .trace("Exception in getSubjectRoles:",e); 
         throw new RuntimeException(e);
      } 
      SecurityContext sc = scb.getSecurityContext();
      
      //Handle the case of Incoming RunAs
      Principal callerPrincipal = null;
      RunAs callerRunAs = sc.getIncomingRunAs();
      if(callerRunAs != null)
      {
         callerPrincipal = new SimplePrincipal(callerRunAs.getName()); 
      }
      
      RoleGroup roles = this.getCurrentRoles(callerPrincipalauthenticatedSubjectsc);
      if(roles == null)
         roles = new SimpleRoleGroup(.);
      return roles
   }  
   
   /*
    * Get the current role group from the security context or
    * the Subject
    * @param principal The Principal in question
    */
   private RoleGroup getCurrentRoles(Principal principal)
   { 
      //Check that the caller is authenticated to the current thread
      Subject subject = SubjectActions.getActiveSubject();  
      
      //Deal with the security context
      SecurityContext sc = SubjectActions.getSecurityContext(); 
      if(sc == null)
      {
         sc = new JBossSecurityContext(); 
         SubjectActions.setSecurityContext(sc);   
      } 
      
      return getCurrentRoles(principal,subject,sc); 
   } 
   
   private RoleGroup getCurrentRoles(Principal principalSubject subjectSecurityContext sc)
   {
      if(subject == null)
         throw new IllegalArgumentException("Subject passed is null");
      if(sc == null)
         throw new IllegalArgumentException("Sec Ctx sc passed is null");
      
      Group subjectRoles = getGroupFromSubject(subject);
      
      boolean emptyContextRoles = false;
      
      RoleGroup userRoles = sc.getUtil().getRoles();
      //Group userRoles = (Group)sc.getData().get(ROLES_IDENTIFIER);
      if(userRoles == null || "true".equalsIgnoreCase(SubjectActions.getRefreshSecurityContextRoles()))
         emptyContextRoles = true;
      userRoles = copyGroups(userRolessubjectRoles); 
      
      
Update the roles in the SecurityContext and allow mapping rules be applied only if the SC roles and the subject roles are not the same
      if(subjectRoles != userRoles || emptyContextRoles)
      { 
         MappingManager mm = sc.getMappingManager();
         MappingContext<RoleGroupmc = mm.getMappingContext(RoleGroup.class);
        
         RoleGroup mappedUserRoles = userRoles;
         if(mc != null && mc.hasModules())
         {
            Map<String,ObjectcontextMap = new HashMap<String,Object>();
            contextMap.put(.userRoles);
            if(principal != null)
              contextMap.put(.principal);
            //Append any deployment role->principals configuration done by the user
            contextMap.put(.,
                  SecurityRolesAssociation.getSecurityRoles());
            
            //Append the principals also
            contextMap.put(.subject.getPrincipals());
            if()
               .trace("Roles before mapping:"userRoles);
            mc.performMapping(contextMapuserRoles);
            mappedUserRoles = (RoleGroupmc.getMappingResult().getMappedObject();
            if()
               .trace("Roles after mapping:"userRoles);
         } 
         sc.getData().put(mappedUserRoles); 
      } 
      
      //Ensure that the security context has the roles
      if(sc.getUtil().getRoles() == null)
         sc.getUtil().setRoles(userRoles);
      //Send the final processed (mapping applied) roles
      return userRoles;   
   }
   
   
Copy the principals from the second group into the first. If the first group is null and the second group is not, the first group will be made equal to the second group

Parameters:
source
toCopy
   private RoleGroup copyGroups(RoleGroup sourceGroup toCopy)
   {
      if(toCopy == null)
         return source;
      if(source == null && toCopy != null
         source = new SimpleRoleGroup(.);
      Enumeration<? extends Principalen = toCopy.members();
      while(en.hasMoreElements())
      {
         source.addRole(new SimpleRole(en.nextElement().getName())); 
      }
       
      return source;
   }
   
   private int internalAuthorization(final Resource resourceSubject subject,
         RoleGroup role)
   {
      .lock();
      try
      {
         if(this. == null)
            this. = new JBossAuthorizationContext(this.);
         return this..authorize(resourcesubjectrole); 
      }
      finally
      {
         .unlock();
      } 
   }
   
   
Get the Subject roles by looking for a Group called 'Roles'

Parameters:
theSubject - the Subject to search for roles
Returns:
the Group contain the subject roles if found, null otherwise
   private Group getGroupFromSubject(Subject theSubject)
   {
      if(theSubject == null)
         throw new IllegalArgumentException("Subject is null");
      Set<GroupsubjectGroups = theSubject.getPrincipals(Group.class);
      Iterator<Groupiter = subjectGroups.iterator();
      Group roles = null;
      whileiter.hasNext() )
      {
         Group grp = (Groupiter.next();
         String name = grp.getName();
         ifname.equals() )
            roles = grp;
      }
      return roles;
   } 
   
   private RoleGroup getRoleGroup(Group roleGroup)
   {
      if(roleGroup == null)
         throw new IllegalArgumentException("roleGroup is null");
      SimpleRoleGroup srg = new SimpleRoleGroup(roleGroup.getName());
      Enumeration<? extends Principalprincipals = roleGroup.members();
      while(principals.hasMoreElements())
      {
         srg.getRoles().add(new SimpleRole(principals.nextElement().getName()));
      }
      return srg;  
   }
   
   private void validateResource(Resource resource)
   {
      if(resource == null)
         throw new IllegalArgumentException("resource is null");
      if(resource.getMap() == null)
         throw new IllegalArgumentException("resource has null context map");
   }
New to GrepCode? Check out our FAQ X