KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > LoginModulesTestCase


1 /*
2  * JBoss, the OpenSource EJB server
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.test;
8
9 import java.lang.reflect.Method JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.Serializable JavaDoc;
12 import java.security.MessageDigest JavaDoc;
13 import java.security.Principal JavaDoc;
14 import java.security.acl.Group JavaDoc;
15 import java.sql.Connection JavaDoc;
16 import java.sql.DriverManager JavaDoc;
17 import java.sql.SQLException JavaDoc;
18 import java.sql.Statement JavaDoc;
19 import java.util.Enumeration JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Set JavaDoc;
23 import java.util.Properties JavaDoc;
24 import javax.naming.InitialContext JavaDoc;
25 import javax.naming.NameAlreadyBoundException JavaDoc;
26 import javax.security.auth.Subject JavaDoc;
27 import javax.security.auth.callback.CallbackHandler JavaDoc;
28 import javax.security.auth.login.AppConfigurationEntry JavaDoc;
29 import javax.security.auth.login.Configuration JavaDoc;
30 import javax.security.auth.login.LoginContext JavaDoc;
31 import javax.security.auth.login.LoginException JavaDoc;
32 import javax.sql.DataSource JavaDoc;
33
34 import junit.framework.TestCase;
35 import junit.framework.TestSuite;
36
37 import org.apache.log4j.Category;
38 import org.apache.log4j.FileAppender;
39 import org.apache.log4j.PatternLayout;
40
41 import org.jboss.logging.XLevel;
42 import org.jboss.security.SimpleGroup;
43 import org.jboss.security.SimplePrincipal;
44 import org.jboss.security.Util;
45 import org.jboss.security.auth.callback.UsernamePasswordHandler;
46 import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
47
48 /** Tests of the LoginModule classes.
49  
50  @author Scott.Stark@jboss.org
51  @version $Revision: 1.7.6.1 $
52  */

53 public class LoginModulesTestCase extends TestCase
54 {
55    static
56    {
57       try
58       {
59          Configuration.setConfiguration(new TestConfig());
60          System.out.println("Installed TestConfig as JAAS Configuration");
61       }
62       catch(Exception JavaDoc e)
63       {
64          e.printStackTrace();
65       }
66    }
67    /** Hard coded login configurations for the test cases. The configuration
68     name corresponds to the unit test function that uses the configuration.
69     */

70    static class TestConfig extends Configuration JavaDoc
71    {
72       public void refresh()
73       {
74       }
75       
76       public AppConfigurationEntry JavaDoc[] getAppConfigurationEntry(String JavaDoc name)
77       {
78          AppConfigurationEntry JavaDoc[] entry = null;
79          try
80          {
81             Class JavaDoc[] parameterTypes = {};
82             Method JavaDoc m = getClass().getDeclaredMethod(name, parameterTypes);
83             Object JavaDoc[] args = {};
84             entry = (AppConfigurationEntry JavaDoc[]) m.invoke(this, args);
85          }
86          catch(Exception JavaDoc e)
87          {
88          }
89          return entry;
90       }
91       AppConfigurationEntry JavaDoc[] testLdap()
92       {
93          String JavaDoc name = "org.jboss.security.auth.spi.LdapLoginModule";
94          HashMap JavaDoc options = new HashMap JavaDoc();
95          options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
96          options.put("java.naming.provider.url", "ldap://siren/");
97          options.put("java.naming.security.authentication", "simple");
98          options.put("principalDNPrefix", "uid=");
99          options.put("principalDNSuffix", ",ou=People,o=starkinternational.com");
100          options.put("rolesCtxDN", "cn=JBossSX Test Roles,ou=Roles,o=starkinternational.com");
101          options.put("uidAttributeID", "userid");
102          options.put("roleAttributeID", "roleName");
103          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
104          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
105          AppConfigurationEntry JavaDoc[] entry = {ace};
106          return entry;
107       }
108
109       AppConfigurationEntry JavaDoc[] testIdentity()
110       {
111          String JavaDoc name = "org.jboss.security.auth.spi.IdentityLoginModule";
112          HashMap JavaDoc options = new HashMap JavaDoc();
113          options.put("principal", "stark");
114          options.put("roles", "Role3,Role4");
115          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
116          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
117          AppConfigurationEntry JavaDoc[] entry = {ace};
118          return entry;
119       }
120       AppConfigurationEntry JavaDoc[] testJdbc()
121       {
122          String JavaDoc name = "org.jboss.security.auth.spi.DatabaseServerLoginModule";
123          HashMap JavaDoc options = new HashMap JavaDoc();
124          options.put("dsJndiName", "testJdbc");
125          options.put("principalsQuery", "select Password from Principals where PrincipalID=?");
126          options.put("rolesQuery", "select Role, RoleGroup from Roles where PrincipalID=?");
127          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
128          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
129          AppConfigurationEntry JavaDoc[] entry = {ace};
130          return entry;
131       }
132       AppConfigurationEntry JavaDoc[] testSimple()
133       {
134          String JavaDoc name = "org.jboss.security.auth.spi.SimpleServerLoginModule";
135          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
136          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap JavaDoc());
137          AppConfigurationEntry JavaDoc[] entry = {ace};
138          return entry;
139       }
140       AppConfigurationEntry JavaDoc[] testUsernamePassword()
141       {
142          return other();
143       }
144       AppConfigurationEntry JavaDoc[] testUsernamePasswordHash()
145       {
146          HashMap JavaDoc options = new HashMap JavaDoc();
147          options.put("hashAlgorithm", "MD5");
148          options.put("hashEncoding", "base64");
149          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(HashTestLoginModule.class.getName(),
150             AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
151          AppConfigurationEntry JavaDoc[] entry = {ace};
152          return entry;
153       }
154       AppConfigurationEntry JavaDoc[] testAnon()
155       {
156          String JavaDoc name = "org.jboss.security.auth.spi.AnonLoginModule";
157          HashMap JavaDoc options = new HashMap JavaDoc();
158          options.put("unauthenticatedIdentity", "nobody");
159          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
160             AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
161          AppConfigurationEntry JavaDoc[] entry = {ace};
162          return entry;
163       }
164       AppConfigurationEntry JavaDoc[] testNull()
165       {
166          String JavaDoc name = "org.jboss.security.auth.spi.AnonLoginModule";
167          HashMap JavaDoc options = new HashMap JavaDoc();
168          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
169          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
170          AppConfigurationEntry JavaDoc[] entry = {ace};
171          return entry;
172       }
173       AppConfigurationEntry JavaDoc[] testUsersRoles()
174       {
175          String JavaDoc name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
176          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
177          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap JavaDoc());
178          AppConfigurationEntry JavaDoc[] entry = {ace};
179          return entry;
180       }
181       AppConfigurationEntry JavaDoc[] testUsersRolesHash()
182       {
183          String JavaDoc name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
184          HashMap JavaDoc options = new HashMap JavaDoc();
185          options.put("usersProperties", "usersb64.properties");
186          options.put("hashAlgorithm", "MD5");
187          options.put("hashEncoding", "base64");
188          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
189          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
190          AppConfigurationEntry JavaDoc[] entry = {ace};
191          return entry;
192       }
193       AppConfigurationEntry JavaDoc[] testAnonUsersRoles()
194       {
195          String JavaDoc name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
196          HashMap JavaDoc options = new HashMap JavaDoc();
197          options.put("unauthenticatedIdentity", "nobody");
198          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(name,
199          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
200          AppConfigurationEntry JavaDoc[] entry = {ace};
201          return entry;
202       }
203       AppConfigurationEntry JavaDoc[] other()
204       {
205          AppConfigurationEntry JavaDoc ace = new AppConfigurationEntry JavaDoc(TestLoginModule.class.getName(),
206          AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap JavaDoc());
207          AppConfigurationEntry JavaDoc[] entry = {ace};
208          return entry;
209       }
210    }
211    public static class TestLoginModule extends UsernamePasswordLoginModule
212    {
213       protected Group JavaDoc[] getRoleSets()
214       {
215          SimpleGroup roles = new SimpleGroup("Roles");
216          Group JavaDoc[] roleSets = {roles};
217          roles.addMember(new SimplePrincipal("TestRole"));
218          roles.addMember(new SimplePrincipal("Role2"));
219          return roleSets;
220       }
221       /** This represents the 'true' password
222        */

223       protected String JavaDoc getUsersPassword()
224       {
225          return "secret";
226       }
227    }
228    public static class HashTestLoginModule extends TestLoginModule
229    {
230       /** This represents the 'true' password in its hashed form
231        */

232       protected String JavaDoc getUsersPassword()
233       {
234          MessageDigest JavaDoc md = null;
235          try
236          {
237             md = MessageDigest.getInstance("MD5");
238          }
239          catch(Exception JavaDoc e)
240          {
241             e.printStackTrace();
242          }
243          byte[] passwordBytes = "secret".getBytes();
244          byte[] hash = md.digest(passwordBytes);
245          String JavaDoc passwordHash = Util.encodeBase64(hash);
246          return passwordHash;
247       }
248    }
249    static class TestDS implements DataSource JavaDoc, Serializable JavaDoc
250    {
251       static final long serialVersionUID = -5464527870557621102L;
252
253       public java.sql.Connection JavaDoc getConnection() throws java.sql.SQLException JavaDoc
254       {
255          return getConnection("sa", "");
256       }
257       public java.sql.Connection JavaDoc getConnection(String JavaDoc user, String JavaDoc pass) throws java.sql.SQLException JavaDoc
258       {
259          String JavaDoc jdbcURL = "jdbc:hsqldb:hsql://localhost:1701";
260          java.sql.Connection JavaDoc con = DriverManager.getConnection(jdbcURL, user, pass);
261          return con;
262       }
263       public java.io.PrintWriter JavaDoc getLogWriter() throws java.sql.SQLException JavaDoc
264       {
265          return null;
266       }
267       public void setLogWriter(java.io.PrintWriter JavaDoc out)
268          throws java.sql.SQLException JavaDoc
269       {
270       }
271       public int getLoginTimeout() throws java.sql.SQLException JavaDoc
272       {
273          return 0;
274       }
275       public void setLoginTimeout(int seconds) throws java.sql.SQLException JavaDoc
276       {
277       }
278    }
279
280    public LoginModulesTestCase(String JavaDoc testName)
281    {
282       super(testName);
283    }
284    
285    protected void setUp() throws Exception JavaDoc
286    {
287       // Set up a simple configuration that logs to LoginModulesTestCase.log
288
Category root = Category.getRoot();
289       root.setLevel(XLevel.TRACE);
290       FileAppender appender = new FileAppender(new PatternLayout("%x%m%n"), "LoginModulesTestCase.log");
291       root.addAppender(appender);
292    }
293
294    public void testUsernamePassword() throws Exception JavaDoc
295    {
296       System.out.println("testUsernamePassword");
297       UsernamePasswordHandler handler = new UsernamePasswordHandler("scott", "secret".toCharArray());
298       LoginContext JavaDoc lc = new LoginContext JavaDoc("testUsernamePassword", handler);
299       lc.login();
300       Subject JavaDoc subject = lc.getSubject();
301       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
302       assertTrue("Principals contains scott", subject.getPrincipals().contains(new SimplePrincipal("scott")));
303       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
304       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
305       assertTrue("TestRole is a role", roles.isMember(new SimplePrincipal("TestRole")));
306       assertTrue("Role2 is a role", roles.isMember(new SimplePrincipal("Role2")));
307       
308       lc.logout();
309    }
310    public void testUsernamePasswordHash() throws Exception JavaDoc
311    {
312       System.out.println("testUsernamePasswordHash");
313       UsernamePasswordHandler handler = new UsernamePasswordHandler("scott", "secret".toCharArray());
314       LoginContext JavaDoc lc = new LoginContext JavaDoc("testUsernamePasswordHash", handler);
315       lc.login();
316       Subject JavaDoc subject = lc.getSubject();
317       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
318       assertTrue("Principals contains scott", subject.getPrincipals().contains(new SimplePrincipal("scott")));
319       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
320       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
321       assertTrue("TestRole is a role", roles.isMember(new SimplePrincipal("TestRole")));
322       assertTrue("Role2 is a role", roles.isMember(new SimplePrincipal("Role2")));
323       
324       lc.logout();
325    }
326
327    public void testUsersRoles() throws Exception JavaDoc
328    {
329       System.out.println("testUsersRoles");
330       UsernamePasswordHandler handler = new UsernamePasswordHandler("scott", "echoman".toCharArray());
331       LoginContext JavaDoc lc = new LoginContext JavaDoc("testUsersRoles", handler);
332       lc.login();
333       Subject JavaDoc subject = lc.getSubject();
334       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
335       assertTrue("Principals contains scott", subject.getPrincipals().contains(new SimplePrincipal("scott")));
336       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
337       assertTrue("Principals contains CallerPrincipal", groups.contains(new SimplePrincipal("CallerPrincipal")));
338       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
339       Iterator JavaDoc groupsIter = groups.iterator();
340       while( groupsIter.hasNext() )
341       {
342          roles = (Group JavaDoc) groupsIter.next();
343          if( roles.getName().equals("Roles") )
344          {
345             assertTrue("Echo is a role", roles.isMember(new SimplePrincipal("Echo")));
346             assertTrue("Java is NOT a role", roles.isMember(new SimplePrincipal("Java")) == false);
347             assertTrue("Coder is NOT a role", roles.isMember(new SimplePrincipal("Coder")) == false);
348          }
349          else if( roles.getName().equals("CallerPrincipal") )
350          {
351             System.out.println("CallerPrincipal is "+roles.members().nextElement());
352             boolean isMember = roles.isMember(new SimplePrincipal("callerScott"));
353             assertTrue("CallerPrincipal is callerScott", isMember);
354          }
355       }
356       lc.logout();
357       
358       handler = new UsernamePasswordHandler("stark", "javaman".toCharArray());
359       lc = new LoginContext JavaDoc("testUsersRoles", handler);
360       lc.login();
361       subject = lc.getSubject();
362       groups = subject.getPrincipals(Group JavaDoc.class);
363       assertTrue("Principals contains stark", subject.getPrincipals().contains(new SimplePrincipal("stark")));
364       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
365       assertTrue("Principals contains CallerPrincipal", groups.contains(new SimplePrincipal("CallerPrincipal")));
366       groupsIter = groups.iterator();
367       while( groupsIter.hasNext() )
368       {
369          roles = (Group JavaDoc) groupsIter.next();
370          if( roles.getName().equals("Roles") )
371          {
372             assertTrue("Echo is NOT a role", roles.isMember(new SimplePrincipal("Echo")) == false);
373             assertTrue("Java is a role", roles.isMember(new SimplePrincipal("Java")));
374             assertTrue("Coder is a role", roles.isMember(new SimplePrincipal("Coder")));
375          }
376          else if( roles.getName().equals("CallerPrincipal") )
377          {
378             System.out.println("CallerPrincipal is "+roles.members().nextElement());
379             boolean isMember = roles.isMember(new SimplePrincipal("callerStark"));
380             assertTrue("CallerPrincipal is callerStark", isMember);
381          }
382       }
383       lc.logout();
384
385       // Test the usernames with common prefix
386
System.out.println("Testing similar usernames");
387       handler = new UsernamePasswordHandler("jdukeman", "anotherduke".toCharArray());
388       lc = new LoginContext JavaDoc("testUsersRoles", handler);
389       lc.login();
390       subject = lc.getSubject();
391       groups = subject.getPrincipals(Group JavaDoc.class);
392       assertTrue("Principals contains jdukeman", subject.getPrincipals().contains(new SimplePrincipal("jdukeman")));
393       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
394       assertTrue("Principals contains CallerPrincipal", groups.contains(new SimplePrincipal("CallerPrincipal")));
395       groupsIter = groups.iterator();
396       while( groupsIter.hasNext() )
397       {
398          roles = (Group JavaDoc) groupsIter.next();
399          if( roles.getName().equals("Roles") )
400          {
401             assertTrue("Role1 is NOT a role", roles.isMember(new SimplePrincipal("Role1")) == false);
402             assertTrue("Role2 is a role", roles.isMember(new SimplePrincipal("Role2")));
403             assertTrue("Role3 is a role", roles.isMember(new SimplePrincipal("Role3")));
404          }
405          else if( roles.getName().equals("CallerPrincipal") )
406          {
407             System.out.println("CallerPrincipal is "+roles.members().nextElement());
408             boolean isMember = roles.isMember(new SimplePrincipal("callerJdukeman"));
409             assertTrue("CallerPrincipal is callerJdukeman", isMember);
410          }
411       }
412       lc.logout();
413    }
414
415    public void testUsersRolesHash() throws Exception JavaDoc
416    {
417       System.out.println("testUsersRolesHash");
418       UsernamePasswordHandler handler = new UsernamePasswordHandler("scott", "echoman".toCharArray());
419       LoginContext JavaDoc lc = new LoginContext JavaDoc("testUsersRolesHash", handler);
420       lc.login();
421       Subject JavaDoc subject = lc.getSubject();
422       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
423       assertTrue("Principals contains scott", subject.getPrincipals().contains(new SimplePrincipal("scott")));
424       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
425       assertTrue("Principals contains CallerPrincipal", groups.contains(new SimplePrincipal("CallerPrincipal")));
426       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
427       Iterator JavaDoc groupsIter = groups.iterator();
428       while( groupsIter.hasNext() )
429       {
430          roles = (Group JavaDoc) groupsIter.next();
431          if( roles.getName().equals("Roles") )
432          {
433             assertTrue("Echo is a role", roles.isMember(new SimplePrincipal("Echo")));
434             assertTrue("Java is NOT a role", roles.isMember(new SimplePrincipal("Java")) == false);
435             assertTrue("Coder is NOT a role", roles.isMember(new SimplePrincipal("Coder")) == false);
436          }
437          else if( roles.getName().equals("CallerPrincipal") )
438          {
439             System.out.println("CallerPrincipal is "+roles.members().nextElement());
440             boolean isMember = roles.isMember(new SimplePrincipal("callerScott"));
441             assertTrue("CallerPrincipal is callerScott", isMember);
442          }
443       }
444       lc.logout();
445    }
446
447    public void testAnonUsersRoles() throws Exception JavaDoc
448    {
449       System.out.println("testAnonUsersRoles");
450       UsernamePasswordHandler handler = new UsernamePasswordHandler(null, null);
451       LoginContext JavaDoc lc = new LoginContext JavaDoc("testAnonUsersRoles", handler);
452       lc.login();
453       Subject JavaDoc subject = lc.getSubject();
454       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
455       assertTrue("Principals contains nobody", subject.getPrincipals().contains(new SimplePrincipal("nobody")));
456       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
457       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
458       assertTrue("Roles has no members", roles.members().hasMoreElements() == false);
459       
460       lc.logout();
461    }
462    public void testAnon() throws Exception JavaDoc
463    {
464       System.out.println("testAnon");
465       UsernamePasswordHandler handler = new UsernamePasswordHandler(null, null);
466       LoginContext JavaDoc lc = new LoginContext JavaDoc("testAnon", handler);
467       lc.login();
468       Subject JavaDoc subject = lc.getSubject();
469       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
470       assertTrue("Principals contains nobody", subject.getPrincipals().contains(new SimplePrincipal("nobody")));
471       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
472       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
473       assertTrue("Roles has no members", roles.members().hasMoreElements() == false);
474       
475       lc.logout();
476    }
477    public void testNull() throws Exception JavaDoc
478    {
479       System.out.println("testNull");
480       UsernamePasswordHandler handler = new UsernamePasswordHandler(null, null);
481       LoginContext JavaDoc lc = new LoginContext JavaDoc("testNull", handler);
482       try
483       {
484          lc.login();
485          fail("Should not be able to login as null, null");
486       }
487       catch(LoginException JavaDoc e)
488       {
489          // Ok
490
}
491    }
492    public void testIdentity() throws Exception JavaDoc
493    {
494       System.out.println("testIdentity");
495       LoginContext JavaDoc lc = new LoginContext JavaDoc("testIdentity");
496       lc.login();
497       Subject JavaDoc subject = lc.getSubject();
498       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
499       assertTrue("Principals contains stark", subject.getPrincipals().contains(new SimplePrincipal("stark")));
500       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
501       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
502       assertTrue("Role2 is not a role", roles.isMember(new SimplePrincipal("Role2")) == false);
503       assertTrue("Role3 is a role", roles.isMember(new SimplePrincipal("Role3")));
504       assertTrue("Role4 is a role", roles.isMember(new SimplePrincipal("Role4")));
505       
506       lc.logout();
507    }
508    public void testSimple() throws Exception JavaDoc
509    {
510       System.out.println("testSimple");
511       UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke", "jduke".toCharArray());
512       LoginContext JavaDoc lc = new LoginContext JavaDoc("testSimple", handler);
513       lc.login();
514       Subject JavaDoc subject = lc.getSubject();
515       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
516       assertTrue("Principals contains jduke", subject.getPrincipals().contains(new SimplePrincipal("jduke")));
517       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
518       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
519       assertTrue("user is a role", roles.isMember(new SimplePrincipal("user")));
520       assertTrue("guest is a role", roles.isMember(new SimplePrincipal("guest")));
521       
522       lc.logout();
523    }
524    public void testLdap() throws Exception JavaDoc
525    {
526       System.out.println("testLdap");
527       UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke", "theduke".toCharArray());
528       LoginContext JavaDoc lc = new LoginContext JavaDoc("testLdap", handler);
529       lc.login();
530       Subject JavaDoc subject = lc.getSubject();
531       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
532       assertTrue("Principals contains jduke", subject.getPrincipals().contains(new SimplePrincipal("jduke")));
533       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
534       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
535       assertTrue("Echo is a role", roles.isMember(new SimplePrincipal("Echo")));
536       assertTrue("TheDuke is a role", roles.isMember(new SimplePrincipal("TheDuke")));
537       
538       lc.logout();
539    }
540    public void testLdapNullPassword() throws Exception JavaDoc
541    {
542       System.out.println("testLdapNullPassword");
543       UsernamePasswordHandler handler = new UsernamePasswordHandler("jduke", null);
544       LoginContext JavaDoc lc = new LoginContext JavaDoc("testLdap", handler);
545       try
546       {
547          // This login should fail
548
lc.login();
549          fail("Was able to login with null password");
550       }
551       catch(LoginException JavaDoc ok)
552       {
553       }
554    }
555
556    /** Use this InstantDB script to setup tables:
557     ; First load the JDBC driver and open a database.
558     d org.enhydra.instantdb.jdbc.idbDriver;
559     o jdbc:idb=/usr/local/src/cvsroot/jBoss/jboss/dist/conf/default/instantdb.properties;
560     
561     ; Create the Principal table
562     e DROP TABLE Principals ;
563     e CREATE TABLE Principals (
564     PrincipalID VARCHAR(64) PRIMARY KEY,
565     Password VARCHAR(64) );
566     
567     ; put some initial data in the table
568     e INSERT INTO Principals VALUES ("scott", "echoman");
569     e INSERT INTO Principals VALUES ("stark", "javaman");
570     
571     ; Create the Roles table
572     e DROP TABLE Roles;
573     e CREATE TABLE Roles (
574     PrincipalID VARCHAR(64) PRIMARY KEY,
575     Role VARCHAR(64),
576     RoleGroup VARCHAR(64) );
577     
578     ; put some initial data in the table
579     e INSERT INTO Roles VALUES ("scott", "Echo", "");
580     e INSERT INTO Roles VALUES ("scott", "caller_scott", "CallerPrincipal");
581     e INSERT INTO Roles VALUES ("stark", "Java", "");
582     e INSERT INTO Roles VALUES ("stark", "Coder", "");
583     e INSERT INTO Roles VALUES ("stark", "caller_stark", "CallerPrincipal");
584     
585     c close;
586     */

587    public void testJdbc() throws Exception JavaDoc
588    {
589       System.out.println("testJdbc");
590       try
591       {
592          Class.forName("org.hsqldb.jdbcDriver");
593       }
594       catch(ClassNotFoundException JavaDoc e)
595       { // Skip the test
596
System.out.println("Skipping test because org.hsqldb.jdbcDriver was not found");
597          return;
598       }
599       // Create a DataSource binding
600
DataSource JavaDoc ds = new TestDS();
601       Properties JavaDoc env = new Properties JavaDoc();
602       org.jnp.server.Main naming = new org.jnp.server.Main();
603       naming.start();
604       System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
605       System.setProperty("java.naming.provider.url", "localhost");
606       InitialContext JavaDoc ctx = new InitialContext JavaDoc(System.getProperties());
607       try
608       {
609          ctx.bind("testJdbc", ds);
610       }
611       catch(NameAlreadyBoundException JavaDoc e)
612       {
613          // Ignore
614
}
615       
616       // Start database and setup tables
617
startHsql();
618       Connection JavaDoc conn = ds.getConnection("sa", "");
619       Statement JavaDoc statement = conn.createStatement();
620       createPrincipalsTable(statement);
621       createRolesTable(statement);
622       statement.close();
623       conn.close();
624       
625       UsernamePasswordHandler handler = new UsernamePasswordHandler("stark", "javaman".toCharArray());
626       LoginContext JavaDoc lc = new LoginContext JavaDoc("testJdbc", handler);
627       lc.login();
628       Subject JavaDoc subject = lc.getSubject();
629       Set JavaDoc groups = subject.getPrincipals(Group JavaDoc.class);
630       assertTrue("Principals contains stark", subject.getPrincipals().contains(new SimplePrincipal("stark")));
631       assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
632       Group JavaDoc roles = (Group JavaDoc) groups.iterator().next();
633       assertTrue("Java is a role", roles.isMember(new SimplePrincipal("Java")));
634       assertTrue("Coder is a role", roles.isMember(new SimplePrincipal("Coder")));
635       
636       lc.logout();
637    }
638    
639    static void startHsql()
640    {
641       // Start DB in new thread, or else it will block us
642
Thread JavaDoc runner = new Thread JavaDoc(new Runnable JavaDoc()
643       {
644          public void run()
645          {
646             File JavaDoc dbDir = new File JavaDoc("hypersonic");
647             dbDir.mkdir();
648             File JavaDoc dbName = new File JavaDoc(dbDir, "DBLogin");
649             // Create startup arguments
650
String JavaDoc[] args = new String JavaDoc[]
651             {
652                "-database", dbName.toString(),
653                "-port", "1701",
654                "-silent", "true",
655                "-trace", "false"
656             };
657             // Start server
658
org.hsqldb.Server.main(args);
659          }
660       });
661       
662       runner.start();
663       System.out.println("HSQL database started");
664    }
665    
666    static void createPrincipalsTable(Statement JavaDoc statement) throws SQLException JavaDoc
667    {
668       try
669       {
670          statement.execute("DROP TABLE Principals");
671       }
672       catch(SQLException JavaDoc e)
673       {
674          // Ok, assume table does not exist
675
}
676       boolean result = statement.execute("CREATE TABLE Principals ("
677       + "PrincipalID VARCHAR(64) PRIMARY KEY,"
678       + "Password VARCHAR(64) )"
679       );
680       System.out.println("Created Principals table, result="+result);
681       result = statement.execute("INSERT INTO Principals VALUES ('scott', 'echoman')");
682       System.out.println("INSERT INTO Principals VALUES ('scott', 'echoman'), result="+result);
683       result = statement.execute("INSERT INTO Principals VALUES ('stark', 'javaman')");
684       System.out.println("INSERT INTO Principals VALUES ('stark', 'javaman'), result="+result);
685    }
686    
687    static void createRolesTable(Statement JavaDoc statement) throws SQLException JavaDoc
688    {
689       try
690       {
691          statement.execute("DROP TABLE Roles");
692       }
693       catch(SQLException JavaDoc e)
694       {
695          // Ok, assume table does not exist
696
}
697       boolean result = statement.execute("CREATE TABLE Roles ("
698       + "PrincipalID VARCHAR(64),"
699       + "Role VARCHAR(64),"
700       + "RoleGroup VARCHAR(64) )"
701       );
702       System.out.println("Created Roles table, result="+result);
703       result = statement.execute("INSERT INTO Roles VALUES ('scott', 'Echo', 'Roles')");
704       System.out.println("INSERT INTO Roles VALUES ('scott', 'Echo', 'Roles'), result="+result);
705       result = statement.execute("INSERT INTO Roles VALUES ('scott', 'callerScott', 'CallerPrincipal')");
706       System.out.println("INSERT INTO Roles VALUES ('scott', 'callerScott', 'CallerPrincipal'), result="+result);
707       result = statement.execute("INSERT INTO Roles VALUES ('stark', 'Java', 'Roles')");
708       System.out.println("INSERT INTO Roles VALUES ('stark', 'Java', 'Roles'), result="+result);
709       result = statement.execute("INSERT INTO Roles VALUES ('stark', 'Coder', 'Roles')");
710       System.out.println("INSERT INTO Roles VALUES ('stark', 'Coder', 'Roles'), result="+result);
711       result = statement.execute("INSERT INTO Roles VALUES ('stark', 'callerStark', 'CallerPrincipal')");
712       System.out.println("INSERT INTO Roles VALUES ('stark', 'callerStark', 'CallerPrincipal'), result="+result);
713    }
714    public static void main(java.lang.String JavaDoc[] args)
715    {
716       System.setErr(System.out);
717       // Print the location of the users.properties resource
718
java.net.URL JavaDoc users = LoginModulesTestCase.class.getResource("/users.properties");
719       System.out.println("users.properties is here: "+users);
720       TestSuite suite = new TestSuite(LoginModulesTestCase.class);
721       junit.textui.TestRunner.run(suite);
722    }
723    
724 }
725
Popular Tags