KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > security > authentication > AuthenticationTest


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.repo.security.authentication;
18
19 import java.io.Serializable JavaDoc;
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.security.MessageDigest JavaDoc;
22 import java.security.NoSuchAlgorithmException JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Map JavaDoc;
26
27 import javax.transaction.UserTransaction JavaDoc;
28
29 import junit.framework.TestCase;
30 import net.sf.acegisecurity.AccountExpiredException;
31 import net.sf.acegisecurity.Authentication;
32 import net.sf.acegisecurity.AuthenticationManager;
33 import net.sf.acegisecurity.BadCredentialsException;
34 import net.sf.acegisecurity.CredentialsExpiredException;
35 import net.sf.acegisecurity.DisabledException;
36 import net.sf.acegisecurity.LockedException;
37 import net.sf.acegisecurity.UserDetails;
38 import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
39 import net.sf.acegisecurity.providers.dao.SaltSource;
40
41 import org.alfresco.model.ContentModel;
42 import org.alfresco.repo.security.permissions.PermissionServiceSPI;
43 import org.alfresco.service.ServiceRegistry;
44 import org.alfresco.service.cmr.dictionary.DictionaryService;
45 import org.alfresco.service.cmr.repository.NodeRef;
46 import org.alfresco.service.cmr.repository.NodeService;
47 import org.alfresco.service.cmr.repository.StoreRef;
48 import org.alfresco.service.cmr.search.SearchService;
49 import org.alfresco.service.cmr.security.AuthenticationService;
50 import org.alfresco.service.namespace.DynamicNamespacePrefixResolver;
51 import org.alfresco.service.namespace.NamespacePrefixResolver;
52 import org.alfresco.service.namespace.NamespaceService;
53 import org.alfresco.service.namespace.QName;
54 import org.alfresco.service.transaction.TransactionService;
55 import org.alfresco.util.ApplicationContextHelper;
56 import org.springframework.context.ApplicationContext;
57
58 public class AuthenticationTest extends TestCase
59 {
60     private static ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
61     
62     private NodeService nodeService;
63
64     private SearchService searchService;
65
66     private NodeRef rootNodeRef;
67
68     private NodeRef systemNodeRef;
69
70     private NodeRef typesNodeRef;
71
72     private NodeRef personAndyNodeRef;
73
74     private DictionaryService dictionaryService;
75
76     private MD4PasswordEncoder passwordEncoder;
77
78     private MutableAuthenticationDao dao;
79
80     private AuthenticationManager authenticationManager;
81
82     private SaltSource saltSource;
83
84     private TicketComponent ticketComponent;
85
86     private AuthenticationService authenticationService;
87     
88     private AuthenticationService pubAuthenticationService;
89
90     private AuthenticationComponent authenticationComponent;
91     
92     private PermissionServiceSPI permissionServiceSPI;
93
94     private UserTransaction JavaDoc userTransaction;
95
96     private AuthenticationComponent authenticationComponentImpl;
97
98     public AuthenticationTest()
99     {
100         super();
101     }
102
103     public AuthenticationTest(String JavaDoc arg0)
104     {
105         super(arg0);
106     }
107
108     public void setUp() throws Exception JavaDoc
109     {
110
111         nodeService = (NodeService) ctx.getBean("nodeService");
112         searchService = (SearchService) ctx.getBean("searchService");
113         dictionaryService = (DictionaryService) ctx.getBean("dictionaryService");
114         passwordEncoder = (MD4PasswordEncoder) ctx.getBean("passwordEncoder");
115         ticketComponent = (TicketComponent) ctx.getBean("ticketComponent");
116         authenticationService = (AuthenticationService) ctx.getBean("authenticationService");
117         pubAuthenticationService = (AuthenticationService) ctx.getBean("AuthenticationService");
118         authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
119         authenticationComponentImpl = (AuthenticationComponent) ctx.getBean("authenticationComponentImpl");
120         permissionServiceSPI = (PermissionServiceSPI) ctx.getBean("permissionService");
121         
122
123         dao = (MutableAuthenticationDao) ctx.getBean("alfDaoImpl");
124         authenticationManager = (AuthenticationManager) ctx.getBean("authenticationManager");
125         saltSource = (SaltSource) ctx.getBean("saltSource");
126
127         TransactionService transactionService = (TransactionService) ctx.getBean(ServiceRegistry.TRANSACTION_SERVICE
128                 .getLocalName());
129         userTransaction = transactionService.getUserTransaction();
130         userTransaction.begin();
131
132         StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
133         rootNodeRef = nodeService.getRootNode(storeRef);
134
135         QName children = ContentModel.ASSOC_CHILDREN;
136         QName system = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "system");
137         QName container = ContentModel.TYPE_CONTAINER;
138         QName types = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "people");
139
140         systemNodeRef = nodeService.createNode(rootNodeRef, children, system, container).getChildRef();
141         typesNodeRef = nodeService.createNode(systemNodeRef, children, types, container).getChildRef();
142         Map JavaDoc<QName, Serializable JavaDoc> props = createPersonProperties("Andy");
143         personAndyNodeRef = nodeService.createNode(typesNodeRef, children, ContentModel.TYPE_PERSON, container, props)
144                 .getChildRef();
145         assertNotNull(personAndyNodeRef);
146
147         deleteAndy();
148         authenticationComponent.clearCurrentSecurityContext();
149
150     }
151
152     private void deleteAndy()
153     {
154         RepositoryAuthenticationDao dao = new RepositoryAuthenticationDao();
155         dao.setNodeService(nodeService);
156         dao.setSearchService(searchService);
157         dao.setDictionaryService(dictionaryService);
158         dao.setNamespaceService(getNamespacePrefixReolsver(""));
159         dao.setPasswordEncoder(passwordEncoder);
160         
161         if(dao.getUserOrNull("andy") != null)
162         {
163             dao.deleteUser("andy");
164         }
165     }
166
167     @Override JavaDoc
168     protected void tearDown() throws Exception JavaDoc
169     {
170         authenticationComponentImpl.clearCurrentSecurityContext();
171         userTransaction.rollback();
172         super.tearDown();
173     }
174
175     private Map JavaDoc<QName, Serializable JavaDoc> createPersonProperties(String JavaDoc userName)
176     {
177         HashMap JavaDoc<QName, Serializable JavaDoc> properties = new HashMap JavaDoc<QName, Serializable JavaDoc>();
178         properties.put(ContentModel.PROP_USERNAME, "Andy");
179         return properties;
180     }
181
182     
183    public void xtestScalability()
184     {
185         long create = 0;
186         long count = 0;
187        
188         long start;
189         long end;
190         authenticationComponent.authenticate("admin", "admin".toCharArray());
191         for(int i = 0; i < 10000; i++)
192         {
193             String JavaDoc id = "TestUser-"+i;
194             start = System.nanoTime();
195             authenticationService.createAuthentication(id, id.toCharArray());
196             end = System.nanoTime();
197             create += (end - start);
198             
199             if((i > 0) && (i % 100 == 0))
200             {
201                 System.out.println("Count = "+i);
202                 System.out.println("Average create : "+(create/i/1000000.0f));
203                 start = System.nanoTime();
204                 dao.userExists(id);
205                 end = System.nanoTime();
206                 System.out.println("Exists : "+((end-start)/1000000.0f));
207             }
208         }
209         authenticationComponent.clearCurrentSecurityContext();
210     }
211     
212     public void testCreateAndyUserAndOtherCRUD() throws NoSuchAlgorithmException JavaDoc, UnsupportedEncodingException JavaDoc
213     {
214         RepositoryAuthenticationDao dao = new RepositoryAuthenticationDao();
215         dao.setNodeService(nodeService);
216         dao.setSearchService(searchService);
217         dao.setDictionaryService(dictionaryService);
218         dao.setNamespaceService(getNamespacePrefixReolsver(""));
219         dao.setPasswordEncoder(passwordEncoder);
220
221         dao.createUser("Andy", "cabbage".toCharArray());
222         assertNotNull(dao.getUserOrNull("Andy"));
223
224         byte[] decodedHash = passwordEncoder.decodeHash(dao.getMD4HashedPassword("Andy"));
225         byte[] testHash = MessageDigest.getInstance("MD4").digest("cabbage".getBytes("UnicodeLittleUnmarked"));
226         assertEquals(new String JavaDoc(decodedHash), new String JavaDoc(testHash));
227
228         UserDetails AndyDetails = (UserDetails) dao.loadUserByUsername("Andy");
229         assertNotNull(AndyDetails);
230         assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", AndyDetails.getUsername());
231         // assertNotNull(dao.getSalt(AndyDetails));
232
assertTrue(AndyDetails.isAccountNonExpired());
233         assertTrue(AndyDetails.isAccountNonLocked());
234         assertTrue(AndyDetails.isCredentialsNonExpired());
235         assertTrue(AndyDetails.isEnabled());
236         assertNotSame("cabbage", AndyDetails.getPassword());
237         assertEquals(AndyDetails.getPassword(), passwordEncoder.encodePassword("cabbage", saltSource
238                 .getSalt(AndyDetails)));
239         assertEquals(1, AndyDetails.getAuthorities().length);
240
241         // Object oldSalt = dao.getSalt(AndyDetails);
242
dao.updateUser("Andy", "carrot".toCharArray());
243         UserDetails newDetails = (UserDetails) dao.loadUserByUsername("Andy");
244         assertNotNull(newDetails);
245         assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", newDetails.getUsername());
246         // assertNotNull(dao.getSalt(newDetails));
247
assertTrue(newDetails.isAccountNonExpired());
248         assertTrue(newDetails.isAccountNonLocked());
249         assertTrue(newDetails.isCredentialsNonExpired());
250         assertTrue(newDetails.isEnabled());
251         assertNotSame("carrot", newDetails.getPassword());
252         assertEquals(1, newDetails.getAuthorities().length);
253
254         assertNotSame(AndyDetails.getPassword(), newDetails.getPassword());
255         // assertNotSame(oldSalt, dao.getSalt(newDetails));
256

257         dao.deleteUser("Andy");
258         assertNull(dao.getUserOrNull("Andy"));
259
260         MessageDigest JavaDoc digester;
261         try
262         {
263             digester = MessageDigest.getInstance("MD4");
264             System.out.println("Digester from " + digester.getProvider());
265         }
266         catch (NoSuchAlgorithmException JavaDoc e)
267         {
268             // TODO Auto-generated catch block
269
e.printStackTrace();
270             System.out.println("No digester");
271         }
272
273     }
274
275     public void testAuthentication()
276     {
277         dao.createUser("GUEST", "".toCharArray());
278
279         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("GUEST", "");
280         token.setAuthenticated(false);
281
282         Authentication result = authenticationManager.authenticate(token);
283         assertNotNull(result);
284
285         dao.createUser("Andy", "squash".toCharArray());
286
287         token = new UsernamePasswordAuthenticationToken("Andy", "squash");
288         token.setAuthenticated(false);
289
290         result = authenticationManager.authenticate(token);
291         assertNotNull(result);
292
293         dao.setEnabled("Andy", false);
294         try
295         {
296             result = authenticationManager.authenticate(token);
297             assertNotNull(result);
298             assertNotNull(null);
299         }
300         catch (DisabledException e)
301         {
302             // Expected
303
}
304
305         dao.setEnabled("Andy", true);
306         result = authenticationManager.authenticate(token);
307         assertNotNull(result);
308
309         dao.setLocked("Andy", true);
310         try
311         {
312             result = authenticationManager.authenticate(token);
313             assertNotNull(result);
314             assertNotNull(null);
315         }
316         catch (LockedException e)
317         {
318             // Expected
319
}
320
321         dao.setLocked("Andy", false);
322         result = authenticationManager.authenticate(token);
323         assertNotNull(result);
324
325         dao.setAccountExpires("Andy", true);
326         dao.setCredentialsExpire("Andy", true);
327         result = authenticationManager.authenticate(token);
328         assertNotNull(result);
329
330         dao.setAccountExpiryDate("Andy", null);
331         dao.setCredentialsExpiryDate("Andy", null);
332         result = authenticationManager.authenticate(token);
333         assertNotNull(result);
334
335         dao.setAccountExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() + 10000));
336         dao.setCredentialsExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() + 10000));
337         result = authenticationManager.authenticate(token);
338         assertNotNull(result);
339
340         dao.setAccountExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() - 10000));
341         try
342         {
343             result = authenticationManager.authenticate(token);
344             assertNotNull(result);
345             assertNotNull(null);
346         }
347         catch (AccountExpiredException e)
348         {
349             // Expected
350
}
351         dao.setAccountExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() + 10000));
352         result = authenticationManager.authenticate(token);
353         assertNotNull(result);
354
355         dao.setCredentialsExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() - 10000));
356         try
357         {
358             result = authenticationManager.authenticate(token);
359             assertNotNull(result);
360             assertNotNull(null);
361         }
362         catch (CredentialsExpiredException e)
363         {
364             // Expected
365
}
366         dao.setCredentialsExpiryDate("Andy", new Date JavaDoc(new Date JavaDoc().getTime() + 10000));
367         result = authenticationManager.authenticate(token);
368         assertNotNull(result);
369
370         dao.deleteUser("Andy");
371         // assertNull(dao.getUserOrNull("Andy"));
372
}
373
374     public void testAuthenticationFailure()
375     {
376         dao.createUser("Andy", "squash".toCharArray());
377
378         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "turnip");
379         token.setAuthenticated(false);
380
381         try
382         {
383             Authentication result = authenticationManager.authenticate(token);
384             assertNotNull(result);
385             assertNotNull(null);
386         }
387         catch (BadCredentialsException e)
388         {
389             // Expected
390
}
391         dao.deleteUser("Andy");
392         // assertNull(dao.getUserOrNull("Andy"));
393
}
394
395     public void testTicket()
396     {
397         dao.createUser("Andy", "ticket".toCharArray());
398
399         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "ticket");
400         token.setAuthenticated(false);
401
402         Authentication result = authenticationManager.authenticate(token);
403         result.setAuthenticated(true);
404
405         String JavaDoc ticket = ticketComponent.getTicket(getUserName(result));
406         String JavaDoc user = ticketComponent.validateTicket(ticket);
407
408         user = null;
409         try
410         {
411             user = ticketComponent.validateTicket("INVALID");
412             assertNotNull(null);
413         }
414         catch (AuthenticationException e)
415         {
416             assertNull(user);
417         }
418
419         ticketComponent.invalidateTicketById(ticket);
420         try
421         {
422             user = ticketComponent.validateTicket(ticket);
423             assertNotNull(null);
424         }
425         catch (AuthenticationException e)
426         {
427
428         }
429
430         dao.deleteUser("Andy");
431         // assertNull(dao.getUserOrNull("Andy"));
432

433     }
434
435     public void testTicketRepeat()
436     {
437         InMemoryTicketComponentImpl tc = new InMemoryTicketComponentImpl();
438         tc.setOneOff(false);
439         tc.setTicketsExpire(false);
440         tc.setValidDuration("P0D");
441
442         dao.createUser("Andy", "ticket".toCharArray());
443
444         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "ticket");
445         token.setAuthenticated(false);
446
447         Authentication result = authenticationManager.authenticate(token);
448         result.setAuthenticated(true);
449
450         String JavaDoc ticket = tc.getTicket(getUserName(result));
451         tc.validateTicket(ticket);
452         tc.validateTicket(ticket);
453
454         dao.deleteUser("Andy");
455         // assertNull(dao.getUserOrNull("Andy"));
456
}
457
458     public void testTicketOneOff()
459     {
460         InMemoryTicketComponentImpl tc = new InMemoryTicketComponentImpl();
461         tc.setOneOff(true);
462         tc.setTicketsExpire(false);
463         tc.setValidDuration("P0D");
464
465         dao.createUser("Andy", "ticket".toCharArray());
466
467         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "ticket");
468         token.setAuthenticated(false);
469
470         Authentication result = authenticationManager.authenticate(token);
471         result.setAuthenticated(true);
472
473         String JavaDoc ticket = tc.getTicket(getUserName(result));
474         tc.validateTicket(ticket);
475         try
476         {
477             tc.validateTicket(ticket);
478             assertNotNull(null);
479         }
480         catch (AuthenticationException e)
481         {
482
483         }
484
485         dao.deleteUser("Andy");
486         // assertNull(dao.getUserOrNull("Andy"));
487
}
488
489     public void testTicketExpires()
490     {
491         InMemoryTicketComponentImpl tc = new InMemoryTicketComponentImpl();
492         tc.setOneOff(false);
493         tc.setTicketsExpire(true);
494         tc.setValidDuration("P5S");
495
496         dao.createUser("Andy", "ticket".toCharArray());
497
498         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "ticket");
499         token.setAuthenticated(false);
500
501         Authentication result = authenticationManager.authenticate(token);
502         result.setAuthenticated(true);
503
504         String JavaDoc ticket = tc.getTicket(getUserName(result));
505         tc.validateTicket(ticket);
506         tc.validateTicket(ticket);
507         tc.validateTicket(ticket);
508         
509         synchronized (this)
510         {
511             try
512             {
513                 wait(10000);
514             }
515             catch (InterruptedException JavaDoc e)
516             {
517                 // TODO Auto-generated catch block
518
e.printStackTrace();
519             }
520         }
521         try
522         {
523             tc.validateTicket(ticket);
524             assertNotNull(null);
525         }
526         catch (AuthenticationException e)
527         {
528
529         }
530         
531         try
532         {
533             tc.validateTicket(ticket);
534             assertNotNull(null);
535         }
536         catch (AuthenticationException e)
537         {
538
539         }
540         
541         try
542         {
543             tc.validateTicket(ticket);
544             assertNotNull(null);
545         }
546         catch (AuthenticationException e)
547         {
548
549         }
550         
551         
552         synchronized (this)
553         {
554             try
555             {
556                 wait(10000);
557             }
558             catch (InterruptedException JavaDoc e)
559             {
560                 // TODO Auto-generated catch block
561
e.printStackTrace();
562             }
563         }
564         
565         try
566         {
567             tc.validateTicket(ticket);
568             assertNotNull(null);
569         }
570         catch (AuthenticationException e)
571         {
572
573         }
574
575         dao.deleteUser("Andy");
576         // assertNull(dao.getUserOrNull("Andy"));
577
}
578
579     public void testTicketDoesNotExpire()
580     {
581         InMemoryTicketComponentImpl tc = new InMemoryTicketComponentImpl();
582         tc.setOneOff(false);
583         tc.setTicketsExpire(true);
584         tc.setValidDuration("P1D");
585
586         dao.createUser("Andy", "ticket".toCharArray());
587
588         UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Andy", "ticket");
589         token.setAuthenticated(false);
590
591         Authentication result = authenticationManager.authenticate(token);
592         result.setAuthenticated(true);
593
594         String JavaDoc ticket = tc.getTicket(getUserName(result));
595         tc.validateTicket(ticket);
596         tc.validateTicket(ticket);
597         tc.validateTicket(ticket);
598         synchronized (this)
599         {
600             try
601             {
602                 wait(10000);
603             }
604             catch (InterruptedException JavaDoc e)
605             {
606                 // TODO Auto-generated catch block
607
e.printStackTrace();
608             }
609         }
610
611         tc.validateTicket(ticket);
612
613         dao.deleteUser("Andy");
614         // assertNull(dao.getUserOrNull("Andy"));
615

616     }
617     
618     public void testAuthenticationService1()
619     {
620         authenticationService.createAuthentication("GUEST", "".toCharArray());
621         authenticationService.authenticate("GUEST", "".toCharArray());
622
623         // create an authentication object e.g. the user
624
authenticationService.createAuthentication("Andy", "auth1".toCharArray());
625
626         // authenticate with this user details
627
authenticationService.authenticate("Andy", "auth1".toCharArray());
628
629         // assert the user is authenticated
630
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
631         // delete the user authentication object
632

633         authenticationService.clearCurrentSecurityContext();
634         authenticationService.deleteAuthentication("Andy");
635
636         // create a new authentication user object
637
authenticationService.createAuthentication("Andy", "auth2".toCharArray());
638         // change the password
639
authenticationService.setAuthentication("Andy", "auth3".toCharArray());
640         // authenticate again to assert password changed
641
authenticationService.authenticate("Andy", "auth3".toCharArray());
642
643         try
644         {
645             authenticationService.authenticate("Andy", "auth1".toCharArray());
646             fail("Authentication should have been rejected");
647         }
648         catch (AuthenticationException e)
649         {
650
651         }
652     }
653     
654     public void testAuthenticationService2()
655     {
656         authenticationService.createAuthentication("GUEST", "".toCharArray());
657         authenticationService.authenticate("GUEST", "".toCharArray());
658
659         // create an authentication object e.g. the user
660
authenticationService.createAuthentication("Andy", "auth1".toCharArray());
661
662         // authenticate with this user details
663
authenticationService.authenticate("Andy", "auth1".toCharArray());
664
665         // assert the user is authenticated
666
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
667         // delete the user authentication object
668

669         authenticationService.clearCurrentSecurityContext();
670         authenticationService.deleteAuthentication("Andy");
671
672         // create a new authentication user object
673
authenticationService.createAuthentication("Andy", "auth2".toCharArray());
674         // change the password
675
authenticationService.setAuthentication("Andy", "auth3".toCharArray());
676         // authenticate again to assert password changed
677
authenticationService.authenticate("Andy", "auth3".toCharArray());
678
679         try
680         {
681             authenticationService.authenticate("Andy", "auth2".toCharArray());
682             fail("Authentication should have been rejected");
683         }
684         catch (AuthenticationException e)
685         {
686
687         }
688     }
689     
690     
691     
692     public void testAuthenticationService3()
693     {
694         authenticationService.createAuthentication("GUEST", "".toCharArray());
695         authenticationService.authenticate("GUEST", "".toCharArray());
696
697         // create an authentication object e.g. the user
698
authenticationService.createAuthentication("Andy", "auth1".toCharArray());
699
700         // authenticate with this user details
701
authenticationService.authenticate("Andy", "auth1".toCharArray());
702
703         // assert the user is authenticated
704
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
705         // delete the user authentication object
706

707         authenticationService.clearCurrentSecurityContext();
708         authenticationService.deleteAuthentication("Andy");
709
710         // create a new authentication user object
711
authenticationService.createAuthentication("Andy", "auth2".toCharArray());
712         // change the password
713
authenticationService.setAuthentication("Andy", "auth3".toCharArray());
714         // authenticate again to assert password changed
715
authenticationService.authenticate("Andy", "auth3".toCharArray());
716
717         authenticationService.authenticate("Andy", "auth3".toCharArray());
718         // get the ticket that represents the current user authentication
719
// instance
720
String JavaDoc ticket = authenticationService.getCurrentTicket();
721         // validate our ticket is still valid
722
authenticationService.validate(ticket);
723
724         // destroy the ticket instance
725
authenticationService.invalidateTicket(ticket);
726         try
727         {
728             authenticationService.validate(ticket);
729             fail("Invalid taicket should have been rejected");
730         }
731         catch (AuthenticationException e)
732         {
733
734         }
735         
736     }
737     
738     public void testAuthenticationService4()
739     {
740         authenticationService.createAuthentication("GUEST", "".toCharArray());
741         authenticationService.authenticate("GUEST", "".toCharArray());
742
743         // create an authentication object e.g. the user
744
authenticationService.createAuthentication("Andy", "auth1".toCharArray());
745
746         // authenticate with this user details
747
authenticationService.authenticate("Andy", "auth1".toCharArray());
748
749         // assert the user is authenticated
750
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
751         // delete the user authentication object
752

753         authenticationService.clearCurrentSecurityContext();
754         authenticationService.deleteAuthentication("Andy");
755
756         // create a new authentication user object
757
authenticationService.createAuthentication("Andy", "auth2".toCharArray());
758         // change the password
759
authenticationService.setAuthentication("Andy", "auth3".toCharArray());
760         // authenticate again to assert password changed
761
authenticationService.authenticate("Andy", "auth3".toCharArray());
762
763         authenticationService.authenticate("Andy", "auth3".toCharArray());
764         // get the ticket that represents the current user authentication
765
// instance
766
String JavaDoc ticket = authenticationService.getCurrentTicket();
767         // validate our ticket is still valid
768

769         authenticationService.clearCurrentSecurityContext();
770         authenticationService.validate(ticket);
771
772         // destroy the ticket instance
773
authenticationService.invalidateTicket(ticket);
774         
775         Authentication current = authenticationComponent.getCurrentAuthentication();
776         if(current != null)
777         {
778             // Still authentication
779
assertTrue(current.isAuthenticated());
780         }
781
782         try
783         {
784             authenticationService.validate(ticket);
785             fail("Invalid ticket should have been rejected");
786         }
787         catch (AuthenticationException e)
788         {
789             assertNull(authenticationComponentImpl.getCurrentAuthentication());
790         }
791
792     }
793     
794     public void testAuthenticationService()
795     {
796         authenticationService.createAuthentication("GUEST", "".toCharArray());
797         authenticationService.authenticate("GUEST", "".toCharArray());
798
799         // create an authentication object e.g. the user
800
authenticationService.createAuthentication("Andy", "auth1".toCharArray());
801
802         // authenticate with this user details
803
authenticationService.authenticate("Andy", "auth1".toCharArray());
804
805         // assert the user is authenticated
806
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
807         // delete the user authentication object
808

809         authenticationService.clearCurrentSecurityContext();
810         authenticationService.deleteAuthentication("Andy");
811
812         // create a new authentication user object
813
authenticationService.createAuthentication("Andy", "auth2".toCharArray());
814         // change the password
815
authenticationService.setAuthentication("Andy", "auth3".toCharArray());
816         // authenticate again to assert password changed
817
authenticationService.authenticate("Andy", "auth3".toCharArray());
818
819       
820         authenticationService.authenticate("Andy", "auth3".toCharArray());
821         // get the ticket that represents the current user authentication
822
// instance
823
String JavaDoc ticket = authenticationService.getCurrentTicket();
824         // validate our ticket is still valid
825
authenticationService.validate(ticket);
826
827         // destroy the ticket instance
828
authenticationService.invalidateTicket(ticket);
829        
830         
831         Authentication current = authenticationComponent.getCurrentAuthentication();
832         if(current != null)
833         {
834             assertTrue(current.isAuthenticated());
835         }
836
837         
838         // clear any context and check we are no longer authenticated
839
authenticationService.clearCurrentSecurityContext();
840         assertNull(authenticationService.getCurrentUserName());
841
842         dao.deleteUser("Andy");
843         // assertNull(dao.getUserOrNull("Andy"));
844
}
845
846     public void testPubAuthenticationService1()
847     {
848         authenticationComponent.setSystemUserAsCurrentUser();
849         pubAuthenticationService.createAuthentication("GUEST", "".toCharArray());
850         authenticationComponent.clearCurrentSecurityContext();
851         
852         pubAuthenticationService.authenticate("GUEST", "".toCharArray());
853
854         // create an authentication object e.g. the user
855

856         authenticationComponent.setSystemUserAsCurrentUser();
857         pubAuthenticationService.createAuthentication("Andy", "auth1".toCharArray());
858         authenticationComponent.clearCurrentSecurityContext();
859
860         // authenticate with this user details
861
pubAuthenticationService.authenticate("Andy", "auth1".toCharArray());
862
863         // assert the user is authenticated
864
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
865         // delete the user authentication object
866

867         pubAuthenticationService.clearCurrentSecurityContext();
868         
869         authenticationComponent.setSystemUserAsCurrentUser();
870         pubAuthenticationService.deleteAuthentication("Andy");
871         authenticationComponent.clearCurrentSecurityContext();
872
873         // create a new authentication user object
874
authenticationComponent.setSystemUserAsCurrentUser();
875         pubAuthenticationService.createAuthentication("Andy", "auth2".toCharArray());
876         // change the password
877
pubAuthenticationService.setAuthentication("Andy", "auth3".toCharArray());
878         authenticationComponent.clearCurrentSecurityContext();
879         // authenticate again to assert password changed
880
pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
881
882         try
883         {
884             pubAuthenticationService.authenticate("Andy", "auth1".toCharArray());
885             fail("Authentication should fail");
886         }
887         catch (AuthenticationException e)
888         {
889
890         }
891         
892     }
893     
894     public void testPubAuthenticationService2()
895     {
896         authenticationComponent.setSystemUserAsCurrentUser();
897         pubAuthenticationService.createAuthentication("GUEST", "".toCharArray());
898         authenticationComponent.clearCurrentSecurityContext();
899         
900         pubAuthenticationService.authenticate("GUEST", "".toCharArray());
901
902         // create an authentication object e.g. the user
903

904         authenticationComponent.setSystemUserAsCurrentUser();
905         pubAuthenticationService.createAuthentication("Andy", "auth1".toCharArray());
906         authenticationComponent.clearCurrentSecurityContext();
907
908         // authenticate with this user details
909
pubAuthenticationService.authenticate("Andy", "auth1".toCharArray());
910
911         // assert the user is authenticated
912
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
913         // delete the user authentication object
914

915         pubAuthenticationService.clearCurrentSecurityContext();
916         
917         authenticationComponent.setSystemUserAsCurrentUser();
918         pubAuthenticationService.deleteAuthentication("Andy");
919         authenticationComponent.clearCurrentSecurityContext();
920
921         // create a new authentication user object
922
authenticationComponent.setSystemUserAsCurrentUser();
923         pubAuthenticationService.createAuthentication("Andy", "auth2".toCharArray());
924         // change the password
925
pubAuthenticationService.setAuthentication("Andy", "auth3".toCharArray());
926         authenticationComponent.clearCurrentSecurityContext();
927         // authenticate again to assert password changed
928
pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
929
930        
931         try
932         {
933             pubAuthenticationService.authenticate("Andy", "auth2".toCharArray());
934             fail("Authentication should fail");
935         }
936         catch (AuthenticationException e)
937         {
938
939         }
940     }
941     
942     
943
944     public void testPubAuthenticationService3()
945     {
946         authenticationComponent.setSystemUserAsCurrentUser();
947         pubAuthenticationService.createAuthentication("GUEST", "".toCharArray());
948         authenticationComponent.clearCurrentSecurityContext();
949         
950         pubAuthenticationService.authenticate("GUEST", "".toCharArray());
951
952         // create an authentication object e.g. the user
953

954         authenticationComponent.setSystemUserAsCurrentUser();
955         pubAuthenticationService.createAuthentication("Andy", "auth1".toCharArray());
956         authenticationComponent.clearCurrentSecurityContext();
957
958         // authenticate with this user details
959
pubAuthenticationService.authenticate("Andy", "auth1".toCharArray());
960
961         // assert the user is authenticated
962
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
963         // delete the user authentication object
964

965         pubAuthenticationService.clearCurrentSecurityContext();
966         
967         authenticationComponent.setSystemUserAsCurrentUser();
968         pubAuthenticationService.deleteAuthentication("Andy");
969         authenticationComponent.clearCurrentSecurityContext();
970
971         // create a new authentication user object
972
authenticationComponent.setSystemUserAsCurrentUser();
973         pubAuthenticationService.createAuthentication("Andy", "auth2".toCharArray());
974         // change the password
975
pubAuthenticationService.setAuthentication("Andy", "auth3".toCharArray());
976         authenticationComponent.clearCurrentSecurityContext();
977         assertNull(authenticationComponent.getCurrentAuthentication());
978         // authenticate again to assert password changed
979
pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
980
981
982         pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
983         // get the ticket that represents the current user authentication
984
// instance
985
String JavaDoc ticket = pubAuthenticationService.getCurrentTicket();
986         authenticationComponent.clearCurrentSecurityContext();
987         assertNull(authenticationComponent.getCurrentAuthentication());
988         
989         // validate our ticket is still valid
990
pubAuthenticationService.validate(ticket);
991
992         // destroy the ticket instance
993
pubAuthenticationService.invalidateTicket(ticket);
994         try
995         {
996             pubAuthenticationService.validate(ticket);
997             fail("Ticket should not validate");
998         }
999         catch (AuthenticationException e)
1000        {
1001
1002        }
1003    }
1004    
1005    public void testPubAuthenticationService()
1006    {
1007        //pubAuthenticationService.authenticateAsGuest();
1008
//authenticationComponent.clearCurrentSecurityContext();
1009

1010        assertNull(authenticationComponent.getCurrentAuthentication());
1011        authenticationComponent.setSystemUserAsCurrentUser();
1012        pubAuthenticationService.createAuthentication("GUEST", "".toCharArray());
1013        authenticationComponent.clearCurrentSecurityContext();
1014        
1015        assertNull(authenticationComponent.getCurrentAuthentication());
1016        pubAuthenticationService.authenticate("GUEST", "".toCharArray());
1017        pubAuthenticationService.authenticate("GUEST", "".toCharArray());
1018        authenticationComponent.clearCurrentSecurityContext();
1019        assertNull(authenticationComponent.getCurrentAuthentication());
1020        
1021   
1022      
1023        pubAuthenticationService.authenticateAsGuest();
1024        authenticationComponent.clearCurrentSecurityContext();
1025        assertNull(authenticationComponent.getCurrentAuthentication());
1026        
1027
1028        // create an authentication object e.g. the user
1029

1030        authenticationComponent.setSystemUserAsCurrentUser();
1031        pubAuthenticationService.createAuthentication("Andy", "auth1".toCharArray());
1032        authenticationComponent.clearCurrentSecurityContext();
1033
1034        // authenticate with this user details
1035
pubAuthenticationService.authenticate("Andy", "auth1".toCharArray());
1036
1037        // assert the user is authenticated
1038
assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
1039        // delete the user authentication object
1040

1041        pubAuthenticationService.clearCurrentSecurityContext();
1042        
1043        authenticationComponent.setSystemUserAsCurrentUser();
1044        pubAuthenticationService.deleteAuthentication("Andy");
1045        authenticationComponent.clearCurrentSecurityContext();
1046
1047        // create a new authentication user object
1048
authenticationComponent.setSystemUserAsCurrentUser();
1049        pubAuthenticationService.createAuthentication("Andy", "auth2".toCharArray());
1050        // change the password
1051
pubAuthenticationService.setAuthentication("Andy", "auth3".toCharArray());
1052        authenticationComponent.clearCurrentSecurityContext();
1053        // authenticate again to assert password changed
1054
pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
1055
1056        pubAuthenticationService.authenticate("Andy", "auth3".toCharArray());
1057        // get the ticket that represents the current user authentication
1058
// instance
1059
String JavaDoc ticket = pubAuthenticationService.getCurrentTicket();
1060        // validate our ticket is still valid
1061
pubAuthenticationService.validate(ticket);
1062
1063        // destroy the ticket instance
1064
pubAuthenticationService.invalidateTicket(ticket);
1065
1066    }
1067
1068    public void testAbstractAuthenticationComponentGuestUserSupport()
1069    {
1070        authenticationComponent.setGuestUserAsCurrentUser();
1071        assertEquals(authenticationComponent.getCurrentUserName(), authenticationComponent.getGuestUserName());
1072    }
1073    
1074    
1075    public void testPassThroughLogin()
1076    {
1077        authenticationService.createAuthentication("Andy", "auth1".toCharArray());
1078
1079        authenticationComponent.setCurrentUser("Andy");
1080        assertEquals(dao.getUserNamesAreCaseSensitive() ? "Andy" : "andy", authenticationService.getCurrentUserName());
1081
1082        //authenticationService.deleteAuthentication("andy");
1083
}
1084
1085    private String JavaDoc getUserName(Authentication authentication)
1086    {
1087        String JavaDoc username = authentication.getPrincipal().toString();
1088
1089        if (authentication.getPrincipal() instanceof UserDetails)
1090        {
1091            username = ((UserDetails) authentication.getPrincipal()).getUsername();
1092        }
1093        return username;
1094    }
1095
1096    private NamespacePrefixResolver getNamespacePrefixReolsver(String JavaDoc defaultURI)
1097    {
1098        DynamicNamespacePrefixResolver nspr = new DynamicNamespacePrefixResolver(null);
1099        nspr.registerNamespace(NamespaceService.SYSTEM_MODEL_PREFIX, NamespaceService.SYSTEM_MODEL_1_0_URI);
1100        nspr.registerNamespace(NamespaceService.CONTENT_MODEL_PREFIX, NamespaceService.CONTENT_MODEL_1_0_URI);
1101        nspr.registerNamespace(ContentModel.USER_MODEL_PREFIX, ContentModel.USER_MODEL_URI);
1102        nspr.registerNamespace("namespace", "namespace");
1103        nspr.registerNamespace(NamespaceService.DEFAULT_PREFIX, defaultURI);
1104        return nspr;
1105    }
1106}
1107
Popular Tags