View Javadoc

1   /*
2   jGuard is a security framework based on top of jaas (java authentication and authorization security).
3   it is written for web applications, to resolve simply, access control problems.
4   version $Name$
5   http://sourceforge.net/projects/jguard/
6   
7   Copyright (C) 2004  Charles GAY
8   
9   This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Lesser General Public
11  License as published by the Free Software Foundation; either
12  version 2.1 of the License, or (at your option) any later version.
13  
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  Lesser General Public License for more details.
18  
19  You should have received a copy of the GNU Lesser General Public
20  License along with this library; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  
23  
24  jGuard project home page:
25  http://sourceforge.net/projects/jguard/
26  
27  */
28  package net.sf.jguard.ext.authentication.manager;
29  
30  import java.security.Principal;
31  import java.util.ArrayList;
32  import java.util.Collection;
33  import java.util.HashMap;
34  import java.util.HashSet;
35  import java.util.Iterator;
36  import java.util.Map;
37  import java.util.Random;
38  import java.util.Set;
39  
40  import java.util.logging.Level;
41  import javax.security.auth.Subject;
42  
43  import net.sf.jguard.core.CoreConstants;
44  import net.sf.jguard.core.PolicyEnforcementPointOptions;
45  import net.sf.jguard.core.authentication.AuthenticationException;
46  import net.sf.jguard.core.authentication.credentials.JGuardCredential;
47  import net.sf.jguard.core.authentication.manager.AuthenticationManager;
48  import net.sf.jguard.core.authentication.manager.AuthenticationManagerFactory;
49  import net.sf.jguard.core.organization.Organization;
50  import net.sf.jguard.core.principals.RolePrincipal;
51  import net.sf.jguard.core.principals.UserPrincipal;
52  import net.sf.jguard.core.provisioning.OrganizationTemplate;
53  import net.sf.jguard.core.provisioning.RegistrationException;
54  import net.sf.jguard.core.provisioning.SubjectTemplate;
55  import net.sf.jguard.ext.SecurityConstants;
56  import net.sf.jguard.core.principals.PrincipalUtils;
57  import net.sf.jguard.ext.util.SubjectUtils;
58  import net.sf.jguard.core.util.XMLUtils;
59  import org.slf4j.Logger;
60  import org.slf4j.LoggerFactory;
61  
62  
63  /**
64   * Abstract class which provides convenient methods for all the
65   * AuthenticationManager implementations.
66   * @author <a href="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
67   * @author <a href="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
68   */
69  public abstract class AbstractAuthenticationManager implements AuthenticationManager {
70  
71  	private static final Logger logger = LoggerFactory.getLogger(AbstractAuthenticationManager.class.getName());
72  
73  	
74          protected OrganizationTemplate organizationTemplate;
75          protected boolean debug = false;
76          
77          private final static String credentialId = "login";
78          private final static String credentialPassword = "password";
79          protected Organization defaultOrganization = null;
80          protected String applicationName;
81  
82  
83  
84      //principals owned by the application
85      protected Set localPrincipalsSet;
86      protected Map localPrincipals;
87      protected Set organizations;
88  
89  	public AbstractAuthenticationManager(Map options) {
90  		super();
91  		localPrincipalsSet= new HashSet();
92  		localPrincipals = new HashMap();
93                  organizations = new HashSet();
94                  applicationName = (String)options.get(PolicyEnforcementPointOptions.APPLICATION_NAME.getLabel());
95  	}
96          
97          public String getApplicationName(){
98              return applicationName;
99          }
100 
101 	
102     protected void importXmlData(Map opts) {
103         String dbPropertiesLocation = (String) opts.get(CoreConstants.AUTHENTICATION_XML_FILE_LOCATION);
104         if(dbPropertiesLocation==null|| "".equals(dbPropertiesLocation)){
105             throw new IllegalArgumentException(CoreConstants.AUTHENTICATION_XML_FILE_LOCATION+" parameter ="+dbPropertiesLocation);
106         }
107         dbPropertiesLocation = XMLUtils.resolveLocation(dbPropertiesLocation);
108         Map options = new HashMap();
109         options.put(PolicyEnforcementPointOptions.APPLICATION_NAME.getLabel(), applicationName);
110         String XmlFileLocation = dbPropertiesLocation.substring(0, dbPropertiesLocation.lastIndexOf('/'))
111                         + "/jGuardUsersPrincipals.xml";
112         options.put(CoreConstants.AUTHENTICATION_XML_FILE_LOCATION, XmlFileLocation);
113         AuthenticationManager authentManager = new XmlAuthenticationManager(options);
114         importAuthenticationManager(authentManager);
115 
116     }
117     public Organization getDefaultOrganization(){
118         //we check that a default organization exists
119         if(defaultOrganization==null){
120             defaultOrganization = findOrganization(SecurityConstants.SYSTEM);
121         }
122         //if no default organization exists, we create a default organization
123         if(defaultOrganization==null){
124             try {
125                 OrganizationTemplate orgTemplate = (OrganizationTemplate) getOrganizationTemplate().clone();
126                 Set credentials = orgTemplate.getCredentials();
127                 Iterator itCredentials = credentials.iterator();
128                 while(itCredentials.hasNext()){
129                     JGuardCredential cred = (JGuardCredential)itCredentials.next();
130                     if(cred.getName().equals(Organization.ID)){
131                         itCredentials.remove();
132                         break;
133                     }
134                 }
135                 JGuardCredential credId = new JGuardCredential(Organization.ID,SecurityConstants.SYSTEM);
136                 credentials.add(credId);
137                 defaultOrganization = createOrganization(orgTemplate);
138             } catch (CloneNotSupportedException ex) {
139                 throw new RuntimeException(ex.getMessage(),ex);
140             } catch (RegistrationException ex) {
141                 throw new RuntimeException(" default organization called 'system' is not present and cannot be created automatically ",ex);
142             }
143         }
144         return defaultOrganization;
145     }
146 
147     public abstract void setOrganizationTemplate(OrganizationTemplate organizationTemplate)throws AuthenticationException;
148     
149     /**
150      * verify the Subject against the provided template and create a user in the XML backend.
151      * @param user Subject to create in the XML backend
152      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#createUser(javax.security.auth.Subject)
153      * @throws AuthenticationException if user already exists
154      */
155     public Subject createUser(SubjectTemplate user,Organization organization) throws RegistrationException {
156     	Subject userCreated = null;
157     	if(organization!= null){
158     		//validate credentials of the SubjectTemplate
159     		organization.getSubjectTemplate().validateTemplate(user);
160     		userCreated = organization.getSubjectTemplate().toSubject(user,organization);
161     	}else{
162     		throw new IllegalArgumentException("organization is  null ");
163     	}
164 
165     	try{
166 	    	if(!userAlreadyExists(userCreated)){
167 	    		//persist the user in the corresponding datasource backend
168 	    		persistUser(userCreated);
169 	    	}else{
170 	    		throw new RegistrationException(" user already exists ");
171 	    	}
172 		}catch(AuthenticationException e){
173 			throw new RegistrationException(e);
174 		}
175 
176         logger.debug(" user persisted \n");
177         return userCreated;
178     }
179 
180     /**
181      * verify the Subject and create a user in the backend.
182      * @param user Subject to create in the backend
183      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#createUser(javax.security.auth.Subject)
184      * @return a Subject containing only the principals owned by the current application.
185      */
186     public Subject createUser(Subject user,Organization organization) throws AuthenticationException {
187     	Set missingCredentials = null;
188     	if(organization!= null){
189     	//we remove unknown credential and return missing credentials
190     	missingCredentials = organization.getSubjectTemplate().validateRequiredCredentialsFromUser(user);
191     	}else{
192     		throw new IllegalArgumentException(" organization is null ");
193     	}
194     	//we remove unknown principals
195     	user.getPrincipals(RolePrincipal.class).retainAll(localPrincipalsSet);
196     	if(missingCredentials.size()==0){
197     		persistUser(user);
198     	}else{
199     		throw new AuthenticationException(" the user cannot be created :some credentials are missing "+missingCredentials);
200     	}
201         return user;
202     }
203 
204     
205      /* verify the Subject and create a user in the XML backend.
206      * @param user Subject to create in the XML backend
207      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#createUser(javax.security.auth.Subject)
208      */
209     public Organization createOrganization(OrganizationTemplate organizationCandidate) throws RegistrationException {
210         OrganizationTemplate ot = this.getOrganizationTemplate();
211         if(ot==null){
212             throw new IllegalStateException(" organizationTemplate is null");
213         }
214     	return createOrganization(ot,organizationCandidate);
215     }
216 
217     /**
218      * verify the organization against the provided template and create an organizationin the XML backend.
219      * @param organizationCandidate
220      * @param organizationTemplate
221      * @throws AuthenticationException if user already exists
222      */
223     public Organization createOrganization(OrganizationTemplate organizationTemplate,OrganizationTemplate organizationCandidate) throws RegistrationException {
224         if(organizationTemplate==null){
225             throw new IllegalStateException(" organizationTemplate is null ");
226         }
227     	Organization organizationCreated = null;
228     	if(organizationCandidate!= null){
229     		//validate credentials of the organizationCandidate
230     		organizationTemplate.validateTemplate(organizationCandidate);
231     		organizationCreated = organizationTemplate.buildOrganization(organizationCandidate);
232     	}else{
233     		organizationCreated = organizationTemplate.toOrganization();
234     	}
235 
236     	try{
237 	    	if(!organizationAlreadyExists(organizationCreated)){
238 	    		//persist the user in the corresponding datasource backend
239 	    		persistOrganization(organizationCreated);
240 	    	}else{
241 	    		throw new RegistrationException(" organization already exists ");
242 	    	}
243 		}catch(AuthenticationException e){
244 			throw new RegistrationException(e);
245 		}
246 
247         logger.debug(" organization persisted \n");
248         return organizationCreated;
249     }
250 
251     
252     /**
253      * create a Principal in the backend, <strong>only</strong> if it is not already present.
254      * @param principal Principal to create in the backend
255      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#createPrincipal(javax.security.auth.Subject)
256      */
257     public void createPrincipal(Principal principal) throws AuthenticationException {
258         if(!localPrincipalsSet.contains(principal) && isRoleAndLocal(principal)){
259         	localPrincipalsSet.add(principal);
260         	localPrincipals.put(principal.getName(),principal);
261         	persistPrincipal(principal);
262         }
263     }
264 
265     /**
266      * persist user in the datasource backend.
267      * @param user
268      */
269     protected abstract void persistUser(Subject user)throws AuthenticationException;
270 
271     /**
272      * persist role in the datasource backend.
273      * @param principal to persist
274      */
275     protected abstract void persistPrincipal(Principal principal) throws AuthenticationException;
276 
277 
278     /**
279      * persist role in the datasource backend.
280      * @param principal to persist
281      */
282     protected abstract void persistOrganization(Organization organization) throws AuthenticationException;
283 
284 
285     /**
286      * get the principals defined in the repository for all the applications.
287      * @return role's list.
288      *
289      */
290     public Set getLocalPrincipals(){
291     	return localPrincipalsSet;
292     }
293 
294     /**
295      * retrieve role from the principals set of the webapp.
296      * @param name
297      * @return role found or null if not found
298      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#getRole(java.lang.String)
299      */
300     public Principal getLocalPrincipal(String name) throws AuthenticationException {
301         Principal ppal = (Principal)localPrincipals.get(name);
302         if(ppal instanceof RolePrincipal){
303         	return (Principal)((RolePrincipal)ppal).clone();
304         }
305         return null;
306     }
307 
308     /**
309      * indicate wether the user exists in the webapp or not.
310      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#userAlreadyExists(javax.security.auth.Subject)
311      * @param user we are looking for
312      * @return true if registered in the webapp, false otherwise
313      */
314     public boolean userAlreadyExists(Subject user) throws AuthenticationException {
315     	
316     	JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
317     	
318     	Subject subject = findUser((String)identityCred.getValue());
319     	if (subject!=null){
320     		return true;
321     	}
322         return false;
323     }
324     
325      /**
326      * indicate wether the organization exists in the webapp or not.
327      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#userAlreadyExists(javax.security.auth.Subject)
328      * @param organization we are looking for
329      * @return true if registered, false otherwise
330      */
331     public boolean organizationAlreadyExists(Organization organization) throws AuthenticationException {
332     	Organization orga = findOrganization(organization.getName());
333     	if (orga!=null){
334     		return true;
335     	}
336         return false;
337     }
338 
339     /**
340      * add a role <strong>present in the webapp</strong> to the registered user.
341      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#addPrincipalToUser(javax.security.auth.Subject, java.lang.String)
342      */
343     public void addPrincipalToUser(Subject user, String roleName) throws AuthenticationException {
344         Principal role = (Principal)localPrincipals.get(roleName);
345         if(role==null){
346         	throw new AuthenticationException(" role "+roleName+" does not exists in the current web application ");
347         }
348         JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
349         user.getPrincipals().add(role);
350         //we update connected users
351         updateUser(identityCred,user);
352     }
353 
354     /**
355      * add a role present in <strong>any</strong> webapp to the registered user.
356      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#addPrincipalToUser(javax.security.auth.Subject, java.lang.String)
357      */
358     public void addPrincipalToUser(Subject user, String roleName,String applicationName) throws AuthenticationException {
359         Principal role = new RolePrincipal(roleName,applicationName);
360         JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
361         user.getPrincipals().add(role);
362         //we update connected users
363         updateUser(identityCred,user);
364     }
365 
366 
367     /**
368      * verify whether or not the role exists in the webapp.
369      * @param role
370      */
371     public boolean hasPrincipal(Principal role) throws AuthenticationException {
372         return localPrincipalsSet.contains(role);
373     }
374 
375     /**
376      * verify whether or not the role exists in the webapp.
377      * @param ppalName Principal's name
378      */
379     public boolean hasPrincipal(String ppalName) throws AuthenticationException {
380         Iterator itPrincipals = localPrincipalsSet.iterator();
381         while(itPrincipals.hasNext()){
382         	Principal ppal = (Principal)itPrincipals.next();
383         	if(ppal.getName().equals(ppalName)){
384         		return true;
385         	}
386         }
387         return false;
388     }
389 
390     public void updateUser(JGuardCredential identityCred,Subject user)throws AuthenticationException{
391     	// remove non-persistant principals
392     	Set principals = user.getPrincipals();
393     	Set userPrincipals = user.getPrincipals(UserPrincipal.class);
394     	boolean userPrincipalFound = false;
395     	Iterator itJexlPrincipals = userPrincipals.iterator();
396     	while(itJexlPrincipals.hasNext()){
397     		Principal userPrincipal = (Principal) itJexlPrincipals.next();
398     		principals.remove(userPrincipal);
399     		userPrincipalFound = true;
400     	}
401 
402     	updateUserImpl(identityCred, user);
403 
404     	// add updated userPrincipal (only if was created previously)
405     	if(userPrincipalFound){
406     		user.getPrincipals().add(new UserPrincipal(user));
407         }
408     }
409 
410     protected abstract void updateUserImpl(JGuardCredential identityCred,Subject user)throws AuthenticationException;
411 
412 
413     /**
414      *  search the users which matches credentials criterions.
415      * @param credentials crierions used to grab the users
416      * @return users found
417      */
418     public abstract Set findUsers(Collection privateCredentials,Collection publicCredentials) throws AuthenticationException;
419 
420 
421     public abstract Set getUsers() throws AuthenticationException;
422 
423 
424     public void importAuthenticationManager(AuthenticationManager authManager){
425     	if(authManager.isEmpty()){
426 			logger.warn(" authManager to import is empty ");
427 			return;
428 		}
429 
430                 
431     	
432     	Set ppals = null;
433         try {
434                 //set OrganizationTemplate
435                 setOrganizationTemplate(authManager.getOrganizationTemplate());
436                 
437                 //import global principals
438                 ppals = authManager.getAllPrincipalsSet();
439         } catch (AuthenticationException e) {
440                 logger.error( " principals cannot be grabbed : ", e);
441         }
442     	Iterator itPrincipals = ppals.iterator();
443     	while(itPrincipals.hasNext()){
444     		Principal ppal = (Principal)itPrincipals.next();
445     		try {
446 			createPrincipal(ppal);
447 		} catch (AuthenticationException e) {
448 			logger.error( " principal cannot persisted : ", e);
449 		}
450     	}
451 
452         //import organizations
453         Set organizationsSet = null;
454         try {
455                 organizationsSet = authManager.getOrganizations();
456                 Iterator itOrganizations = organizationsSet.iterator();
457                 while(itOrganizations.hasNext()){
458                         Organization orga = (Organization)itOrganizations.next();
459 
460                                 createOrganization(orga);
461 
462                 }
463              
464                 
465         } catch (AuthenticationException e) {
466                         logger.error( " principal cannot persisted : ", e);
467         }
468 
469         
470         
471     	//import users
472     	Set usersSet;
473 		try {
474 			usersSet = authManager.getUsers();
475                         Iterator itUsers = usersSet.iterator();
476                         while(itUsers.hasNext()){
477                            Subject user = (Subject)itUsers.next();
478                            persistUser(user);
479 			}
480 
481 		} catch (AuthenticationException e) {
482 			logger.error( " default subject template cannot be persisted : ", e);
483 		}
484 
485     }
486 
487 
488 	/**
489 	 * extract credentials sought
490 	 * @param credentials Ids Sought
491 	 * @param credentials
492 	 * @return
493 	 */
494 	protected Set extractCredentials(Set credentialsIdSought, Set credentials) {
495 		 Set credentialsFromSubject  = new HashSet();
496 		Iterator itCred = credentials.iterator();
497 		while(itCred.hasNext()){
498 			JGuardCredential cred = (JGuardCredential)itCred.next();
499 			String credId = cred.getName();
500 			Iterator itCredInvolved = credentialsIdSought.iterator();
501 			while(itCredInvolved.hasNext()){
502 				String idSought = (String)itCredInvolved.next();
503 				if(idSought.equals(credId)){
504 					credentialsFromSubject.add(cred);
505 				}
506 			}
507 		}
508 		return credentialsFromSubject;
509 	}
510 
511 	protected Set extractCredentialsFromSubject(Set credentialsSought,Subject user){
512 		 Set credentialsFromSubject  = new HashSet();
513 		 credentialsFromSubject.addAll(extractCredentials(credentialsSought,user.getPublicCredentials(JGuardCredential.class)));
514 		 credentialsFromSubject.addAll(extractCredentials(credentialsSought,user.getPrivateCredentials(JGuardCredential.class)));
515 		 return credentialsFromSubject;
516 	}
517 
518     protected JGuardCredential extractIdentityCredentialFromUser(Subject user) throws AuthenticationException{
519     	Set creds = new HashSet();
520     	creds.add(getCredentialId());
521     	 Set credsFound = extractCredentialsFromSubject(creds,user);
522     	 if(credsFound.size()>1){
523     		 throw new IllegalArgumentException(" the user has got more than one identity argument ");
524     	 }else if (credsFound.size()<1){
525     		 throw new IllegalArgumentException(" the user has'nt got  one identity argument ");
526     	 }else{
527     		 return (JGuardCredential)credsFound.iterator().next();
528     	 }
529     }
530 
531     /**
532      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#clonePrincipal(String roleName)
533      */
534     public Principal clonePrincipal(String roleName) throws AuthenticationException {
535         Random rnd = new Random();
536         String cloneName = roleName+rnd.nextInt(99999);
537 
538         return clonePrincipal(roleName, cloneName);
539     }
540 
541     /**
542      * @see net.sf.jguard.core.authentication.manager.AuthenticationManager#clonePrincipal(String roleName, String cloneName)
543      */
544     public Principal clonePrincipal(String roleName, String cloneName) throws AuthenticationException {
545     	Principal role = (Principal)localPrincipals.get(roleName);
546     	Principal clone = null;
547     	if(role instanceof RolePrincipal) {
548             clone = (RolePrincipal)((RolePrincipal)role).clone();
549             ((RolePrincipal)clone).setName(cloneName);
550     	}
551     	else{
552     		clone = PrincipalUtils.getPrincipal(role.getClass().getName(), cloneName);
553         }
554         //persist the newly created clone
555         createPrincipal(clone);
556 
557     return clone;
558     }
559     
560     /**
561      * change 'active' property on the specified role for a user.
562      * this change cannot be done on 'guest' user, or if it remains only one 'active=true' role.
563      * @param subject
564      * @param roleName
565      * @param applicationName
566      * @param active
567      * @throws AuthenticationException
568      */
569     public void setActiveOnRolePrincipal(Subject subject,String roleName,String applicationName,boolean active) throws AuthenticationException{
570     	//guest users cannot change their 'guest' role.
571     	if(roleName.equals(CoreConstants.GUEST)){
572     		throw new AuthenticationException(CoreConstants.GUEST+" 'active' property cannot be modified  ");
573     	}
574     	JGuardCredential identityCredential = extractIdentityCredentialFromUser(subject);
575     	if(!active && !checkMultipleActiveRoleExists(subject)){
576     		throw new AuthenticationException("only one role is active from the same application. user cannot inactivate it ");
577     	}
578     	Principal principal = getRole(subject, roleName, applicationName);
579     	if(principal instanceof RolePrincipal){
580     		RolePrincipal role = (RolePrincipal)principal;
581     		role.setActive(active);
582     		updateUser(identityCredential, subject);
583     	}else{
584     		logger.warn("active can only be applied to RolePrincipal");
585     	}
586     }
587     
588     public Principal getRole(Subject subject,String roleName,String applicationName) throws AuthenticationException{
589     	if(roleName == null || roleName.equals("")){
590     		throw new AuthenticationException("roleName is null or empty");
591     	}
592     	if(applicationName == null || applicationName.equals("")){
593     		throw new AuthenticationException("applicationName is null or empty");
594     	}
595     	Set principals = subject.getPrincipals();
596     	Iterator it = principals.iterator();
597     	Principal principalFound = null;
598     	while(it.hasNext()){
599     		Principal principal = (Principal)it.next();
600     			if(roleName.equals(principal.getName())){
601     				principalFound = principal;
602     				break;
603     			}
604     		
605     	}
606     	if(principalFound == null){
607     		throw new AuthenticationException("  role not found with name="+roleName+" and applicationName="+applicationName);
608     	}
609     	return principalFound;
610     }
611     
612     /**
613      * check that user owns multiple 'active' roles from the <u>same</u> application.
614      * @param subject
615      * @return
616      */
617     private boolean checkMultipleActiveRoleExists(Subject subject){
618     	Set principals = subject.getPrincipals();
619     	Iterator it = principals.iterator();
620     	int activeRoles = 0;
621     	while(it.hasNext()){
622     		Principal principal = (Principal)it.next();
623     		
624     		if(principal instanceof RolePrincipal){
625     			RolePrincipal rPrincipal =null;
626     			rPrincipal = (RolePrincipal)principal;
627     			if(rPrincipal.isActive() && this.applicationName.equals(rPrincipal.getApplicationName())){
628     				activeRoles++;
629     			}
630     		}
631     		
632     	}
633     	if(activeRoles>1){
634     		return true;
635     	}
636     	return false;
637     }
638 
639     /**
640      * finds a user with a private Credential with name='login' and value= parameter of this method.
641      * @param login
642      * @param am
643      * @return Subject
644      */
645     public Subject findUser(String login) {
646                 Set credentials = new HashSet();
647                 Subject user = null;
648        try {
649 		JGuardCredential jcred = new JGuardCredential();
650                 jcred.setName(getCredentialId());
651 		jcred.setValue(login);
652 		credentials.add(jcred);
653         	
654         	Collection usersFound = findUsers(credentials,new ArrayList());
655     		Iterator itUsers = usersFound.iterator();
656     		if(itUsers.hasNext()){
657     			user = (Subject)itUsers.next();
658     		}else{
659     			throw new AuthenticationException(" no user found ");
660     		}
661         } catch (AuthenticationException e) {
662             logger.warn( e.getLocalizedMessage());
663         }
664 
665         return user;
666     }
667     
668     public void updateRoleDefinition(Subject subject,String roleName,String applicationName,String definition) throws AuthenticationException {
669     	   RolePrincipal ppal = (RolePrincipal)getRole(subject,roleName,applicationName);
670     	   ppal.setDefinition(definition);
671     	   JGuardCredential identity = SubjectUtils.getIdentityCredential(subject,this);
672     	   AuthenticationManagerFactory.getAuthenticationManager().updateUser(identity, subject);
673 
674     }
675 
676     public String getCredentialId() {
677         return credentialId;
678     }
679 
680    
681     /**
682      * @return a cloned version  of the OrganizationTemplate.
683      */
684     public OrganizationTemplate getOrganizationTemplate() {
685         try {
686             return (OrganizationTemplate) organizationTemplate.clone();
687         } catch (CloneNotSupportedException ex) {
688            throw new IllegalStateException("organizationtemplate cannot be cloned "+ex.getMessage());
689         }
690     }
691 
692     private Organization createOrganization(Organization orga) throws RegistrationException {
693         return createOrganization(new OrganizationTemplate(orga));
694     }
695 
696     /**
697      * return true if the principal is an instance of a class or subclass
698      * of RolePrincipal and if its applicationName is equals to the name 
699      * of the running application.
700      * @param principal
701      * @return
702      */
703     protected boolean isRoleAndLocal(Principal principal){
704         if(applicationName == null){
705             throw new IllegalStateException(" applicationName is null and must be defined ");
706         }
707         if(isRole(principal)){
708             RolePrincipal role = (RolePrincipal)principal;
709             if(applicationName.equals(role.getApplicationName())){
710             return true;
711             }
712         }
713         return false;
714     }
715     
716     protected boolean isRole(Principal principal){
717         if(principal.getClass().isAssignableFrom(RolePrincipal.class)){
718             return true;
719         }
720         return false;
721     }
722 
723      public String getCredentialPassword() {
724         return credentialPassword;
725     }
726     
727 }