1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
65
66
67
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
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
119 if(defaultOrganization==null){
120 defaultOrganization = findOrganization(SecurityConstants.SYSTEM);
121 }
122
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
151
152
153
154
155 public Subject createUser(SubjectTemplate user,Organization organization) throws RegistrationException {
156 Subject userCreated = null;
157 if(organization!= null){
158
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
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
182
183
184
185
186 public Subject createUser(Subject user,Organization organization) throws AuthenticationException {
187 Set missingCredentials = null;
188 if(organization!= null){
189
190 missingCredentials = organization.getSubjectTemplate().validateRequiredCredentialsFromUser(user);
191 }else{
192 throw new IllegalArgumentException(" organization is null ");
193 }
194
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
206
207
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
219
220
221
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
230 organizationTemplate.validateTemplate(organizationCandidate);
231 organizationCreated = organizationTemplate.buildOrganization(organizationCandidate);
232 }else{
233 organizationCreated = organizationTemplate.toOrganization();
234 }
235
236 try{
237 if(!organizationAlreadyExists(organizationCreated)){
238
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
254
255
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
267
268
269 protected abstract void persistUser(Subject user)throws AuthenticationException;
270
271
272
273
274
275 protected abstract void persistPrincipal(Principal principal) throws AuthenticationException;
276
277
278
279
280
281
282 protected abstract void persistOrganization(Organization organization) throws AuthenticationException;
283
284
285
286
287
288
289
290 public Set getLocalPrincipals(){
291 return localPrincipalsSet;
292 }
293
294
295
296
297
298
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
310
311
312
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
327
328
329
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
341
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
351 updateUser(identityCred,user);
352 }
353
354
355
356
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
363 updateUser(identityCred,user);
364 }
365
366
367
368
369
370
371 public boolean hasPrincipal(Principal role) throws AuthenticationException {
372 return localPrincipalsSet.contains(role);
373 }
374
375
376
377
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
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
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
415
416
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
435 setOrganizationTemplate(authManager.getOrganizationTemplate());
436
437
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
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
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
490
491
492
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
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
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
555 createPrincipal(clone);
556
557 return clone;
558 }
559
560
561
562
563
564
565
566
567
568
569 public void setActiveOnRolePrincipal(Subject subject,String roleName,String applicationName,boolean active) throws AuthenticationException{
570
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
614
615
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
641
642
643
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
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
698
699
700
701
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 }