Source Code Cross Referenced for LoginModulesUnitTestCase.java in  » EJB-Server-JBoss-4.2.1 » testsuite » org » jboss » test » security » test » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » EJB Server JBoss 4.2.1 » testsuite » org.jboss.test.security.test 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * JBoss, Home of Professional Open Source.
0003:         * Copyright 2006, Red Hat Middleware LLC, and individual contributors
0004:         * as indicated by the @author tags. See the copyright.txt file in the
0005:         * distribution for a full listing of individual contributors.
0006:         *
0007:         * This is free software; you can redistribute it and/or modify it
0008:         * under the terms of the GNU Lesser General Public License as
0009:         * published by the Free Software Foundation; either version 2.1 of
0010:         * the License, or (at your option) any later version.
0011:         *
0012:         * This software is distributed in the hope that it will be useful,
0013:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
0014:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
0015:         * Lesser General Public License for more details.
0016:         *
0017:         * You should have received a copy of the GNU Lesser General Public
0018:         * License along with this software; if not, write to the Free
0019:         * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
0020:         * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
0021:         */
0022:        package org.jboss.test.security.test;
0023:
0024:        import java.lang.reflect.Method;
0025:        import java.io.Serializable;
0026:        import java.io.IOException;
0027:        import java.security.MessageDigest;
0028:        import java.security.Principal;
0029:        import java.security.KeyStore;
0030:        import java.security.cert.X509Certificate;
0031:        import java.security.acl.Group;
0032:        import java.sql.Connection;
0033:        import java.sql.DriverManager;
0034:        import java.sql.SQLException;
0035:        import java.sql.Statement;
0036:        import java.util.Enumeration;
0037:        import java.util.HashMap;
0038:        import java.util.Iterator;
0039:        import java.util.Set;
0040:        import java.net.URL;
0041:        import javax.naming.InitialContext;
0042:        import javax.security.auth.Subject;
0043:        import javax.security.auth.login.AppConfigurationEntry;
0044:        import javax.security.auth.login.Configuration;
0045:        import javax.security.auth.login.LoginContext;
0046:        import javax.security.auth.login.LoginException;
0047:        import javax.sql.DataSource;
0048:        import javax.resource.spi.security.PasswordCredential;
0049:        import javax.management.MBeanServerFactory;
0050:        import javax.management.MBeanServer;
0051:        import javax.management.ObjectName;
0052:        import javax.net.ssl.KeyManagerFactory;
0053:        import javax.net.ssl.TrustManagerFactory;
0054:
0055:        import junit.framework.TestSuite;
0056:
0057:        import org.apache.log4j.Logger;
0058:
0059:        import org.jboss.logging.XLevel;
0060:        import org.jboss.security.SimpleGroup;
0061:        import org.jboss.security.SimplePrincipal;
0062:        import org.jboss.security.Util;
0063:        import org.jboss.security.SecurityAssociation;
0064:        import org.jboss.security.SecurityDomain;
0065:        import org.jboss.security.plugins.JaasSecurityDomain;
0066:        import org.jboss.security.auth.callback.UsernamePasswordHandler;
0067:        import org.jboss.security.auth.callback.SecurityAssociationHandler;
0068:        import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
0069:        import org.jboss.test.JBossTestCase;
0070:
0071:        /** Tests of the LoginModule classes.
0072:
0073:         @author Scott.Stark@jboss.org
0074:         @version $Revision: 57211 $
0075:         */
0076:        public class LoginModulesUnitTestCase extends JBossTestCase {
0077:
0078:            /** Hard coded login configurations for the test cases. The configuration
0079:             name corresponds to the unit test function that uses the configuration.
0080:             */
0081:            static class TestConfig extends Configuration {
0082:                public void refresh() {
0083:                }
0084:
0085:                public AppConfigurationEntry[] getAppConfigurationEntry(
0086:                        String name) {
0087:                    AppConfigurationEntry[] entry = null;
0088:                    try {
0089:                        Class[] parameterTypes = {};
0090:                        Method m = getClass().getDeclaredMethod(name,
0091:                                parameterTypes);
0092:                        Object[] args = {};
0093:                        entry = (AppConfigurationEntry[]) m.invoke(this , args);
0094:                    } catch (Exception e) {
0095:                    }
0096:                    return entry;
0097:                }
0098:
0099:                AppConfigurationEntry[] testClientLogin() {
0100:                    String name = "org.jboss.security.ClientLoginModule";
0101:                    HashMap options = new HashMap();
0102:                    options.put("restore-login-identity", "true");
0103:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0104:                            name,
0105:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0106:                            options);
0107:                    AppConfigurationEntry[] entry = { ace };
0108:                    return entry;
0109:                }
0110:
0111:                AppConfigurationEntry[] testIdentity() {
0112:                    String name = "org.jboss.security.auth.spi.IdentityLoginModule";
0113:                    HashMap options = new HashMap();
0114:                    options.put("principal", "stark");
0115:                    options.put("roles", "Role3,Role4");
0116:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0117:                            name,
0118:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0119:                            options);
0120:                    AppConfigurationEntry[] entry = { ace };
0121:                    return entry;
0122:                }
0123:
0124:                AppConfigurationEntry[] testJdbc() {
0125:                    String name = "org.jboss.security.auth.spi.DatabaseServerLoginModule";
0126:                    HashMap options = new HashMap();
0127:                    options.put("dsJndiName", "testJdbc");
0128:                    options
0129:                            .put("principalsQuery",
0130:                                    "select Password from Principals where PrincipalID=?");
0131:                    options
0132:                            .put("rolesQuery",
0133:                                    "select Role, RoleGroup from Roles where PrincipalID=?");
0134:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0135:                            name,
0136:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0137:                            options);
0138:                    AppConfigurationEntry[] entry = { ace };
0139:                    return entry;
0140:                }
0141:
0142:                AppConfigurationEntry[] testSimple() {
0143:                    String name = "org.jboss.security.auth.spi.SimpleServerLoginModule";
0144:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0145:                            name,
0146:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0147:                            new HashMap());
0148:                    AppConfigurationEntry[] entry = { ace };
0149:                    return entry;
0150:                }
0151:
0152:                AppConfigurationEntry[] testUsernamePassword() {
0153:                    return other();
0154:                }
0155:
0156:                AppConfigurationEntry[] testUsernamePasswordHash() {
0157:                    HashMap options = new HashMap();
0158:                    options.put("hashAlgorithm", "MD5");
0159:                    options.put("hashEncoding", "base64");
0160:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0161:                            HashTestLoginModule.class.getName(),
0162:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0163:                            options);
0164:                    AppConfigurationEntry[] entry = { ace };
0165:                    return entry;
0166:                }
0167:
0168:                AppConfigurationEntry[] testUsernamePasswordHashWithDigestCallback() {
0169:                    HashMap options = new HashMap();
0170:                    options.put("hashAlgorithm", "MD5");
0171:                    options.put("hashEncoding", "base64");
0172:                    options.put("hashCharset", "UTF-8");
0173:                    options.put("digestCallback",
0174:                            "org.jboss.test.security.test.TestDigestCallback");
0175:                    options.put("digest.preSalt", "pre");
0176:                    options.put("digest.postSalt", "post");
0177:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0178:                            HashTestDigestCallbackLoginModule.class.getName(),
0179:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0180:                            options);
0181:                    AppConfigurationEntry[] entry = { ace };
0182:                    return entry;
0183:                }
0184:
0185:                AppConfigurationEntry[] testAnon() {
0186:                    String name = "org.jboss.security.auth.spi.AnonLoginModule";
0187:                    HashMap options = new HashMap();
0188:                    options.put("unauthenticatedIdentity", "nobody");
0189:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0190:                            name,
0191:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0192:                            options);
0193:                    AppConfigurationEntry[] entry = { ace };
0194:                    return entry;
0195:                }
0196:
0197:                AppConfigurationEntry[] testNull() {
0198:                    String name = "org.jboss.security.auth.spi.AnonLoginModule";
0199:                    HashMap options = new HashMap();
0200:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0201:                            name,
0202:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0203:                            options);
0204:                    AppConfigurationEntry[] entry = { ace };
0205:                    return entry;
0206:                }
0207:
0208:                AppConfigurationEntry[] testUsersRoles() {
0209:                    String name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
0210:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0211:                            name,
0212:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0213:                            new HashMap());
0214:                    AppConfigurationEntry[] entry = { ace };
0215:                    return entry;
0216:                }
0217:
0218:                AppConfigurationEntry[] testUsersRolesHash() {
0219:                    String name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
0220:                    HashMap options = new HashMap();
0221:                    options.put("usersProperties", "usersb64.properties");
0222:                    options.put("hashAlgorithm", "MD5");
0223:                    options.put("hashEncoding", "base64");
0224:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0225:                            name,
0226:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0227:                            options);
0228:                    AppConfigurationEntry[] entry = { ace };
0229:                    return entry;
0230:                }
0231:
0232:                AppConfigurationEntry[] testAnonUsersRoles() {
0233:                    String name = "org.jboss.security.auth.spi.UsersRolesLoginModule";
0234:                    HashMap options = new HashMap();
0235:                    options.put("unauthenticatedIdentity", "nobody");
0236:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0237:                            name,
0238:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0239:                            options);
0240:                    AppConfigurationEntry[] entry = { ace };
0241:                    return entry;
0242:                }
0243:
0244:                AppConfigurationEntry[] testControlFlags() {
0245:                    String name1 = "org.jboss.security.auth.spi.UsersRolesLoginModule";
0246:                    AppConfigurationEntry ace1 = new AppConfigurationEntry(
0247:                            name1,
0248:                            AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT,
0249:                            new HashMap());
0250:
0251:                    String name2 = "org.jboss.security.auth.spi.DatabaseServerLoginModule";
0252:                    HashMap options = new HashMap();
0253:                    options.put("dsJndiName", "testJdbc");
0254:                    options
0255:                            .put("principalsQuery",
0256:                                    "select Password from Principals where PrincipalID=?");
0257:                    options
0258:                            .put("rolesQuery",
0259:                                    "select Role, RoleGroup from Roles where PrincipalID=?");
0260:                    AppConfigurationEntry ace2 = new AppConfigurationEntry(
0261:                            name2,
0262:                            AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT,
0263:                            options);
0264:
0265:                    AppConfigurationEntry[] entry = { ace1, ace2 };
0266:                    return entry;
0267:                }
0268:
0269:                AppConfigurationEntry[] testJCACallerIdentity() {
0270:                    String name = "org.jboss.resource.security.CallerIdentityLoginModule";
0271:                    HashMap options = new HashMap();
0272:                    options.put("userName", "jduke");
0273:                    options.put("password", "theduke");
0274:                    options.put("managedConnectionFactoryName",
0275:                            "jboss:name=fakeMCF");
0276:                    options.put("ignoreMissigingMCF", Boolean.TRUE);
0277:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0278:                            name,
0279:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0280:                            options);
0281:                    AppConfigurationEntry[] entry = { ace };
0282:                    return entry;
0283:                }
0284:
0285:                AppConfigurationEntry[] testJaasSecurityDomainIdentityLoginModule() {
0286:                    String name = "org.jboss.resource.security.JaasSecurityDomainIdentityLoginModule";
0287:                    HashMap options = new HashMap();
0288:                    options.put("userName", "sa");
0289:                    options.put("password", "E5gtGMKcXPP");
0290:                    options.put("managedConnectionFactoryName",
0291:                            "jboss.jca:service=LocalTxCM,name=DefaultDS");
0292:                    options.put("ignoreMissigingMCF", Boolean.TRUE);
0293:                    options
0294:                            .put(
0295:                                    "jaasSecurityDomain",
0296:                                    "jboss.test:service=JaasSecurityDomain,domain=testJaasSecurityDomainIdentityLoginModule");
0297:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0298:                            name,
0299:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0300:                            options);
0301:                    AppConfigurationEntry[] entry = { ace };
0302:                    return entry;
0303:                }
0304:
0305:                AppConfigurationEntry[] testCertLogin() {
0306:                    String name = "org.jboss.security.auth.spi.BaseCertLoginModule";
0307:                    HashMap options = new HashMap();
0308:                    options.put("securityDomain", "testCertLogin");
0309:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0310:                            name,
0311:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0312:                            options);
0313:                    AppConfigurationEntry[] entry = { ace };
0314:                    return entry;
0315:                }
0316:
0317:                AppConfigurationEntry[] testCertRoles() {
0318:                    String name = "org.jboss.security.auth.spi.CertRolesLoginModule";
0319:                    HashMap options = new HashMap();
0320:                    options.put("securityDomain", "testCertRoles");
0321:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0322:                            name,
0323:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0324:                            options);
0325:                    AppConfigurationEntry[] entry = { ace };
0326:                    return entry;
0327:                }
0328:
0329:                AppConfigurationEntry[] other() {
0330:                    AppConfigurationEntry ace = new AppConfigurationEntry(
0331:                            TestLoginModule.class.getName(),
0332:                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
0333:                            new HashMap());
0334:                    AppConfigurationEntry[] entry = { ace };
0335:                    return entry;
0336:                }
0337:            }
0338:
0339:            public static class TestLoginModule extends
0340:                    UsernamePasswordLoginModule {
0341:                protected Group[] getRoleSets() {
0342:                    SimpleGroup roles = new SimpleGroup("Roles");
0343:                    Group[] roleSets = { roles };
0344:                    roles.addMember(new SimplePrincipal("TestRole"));
0345:                    roles.addMember(new SimplePrincipal("Role2"));
0346:                    return roleSets;
0347:                }
0348:
0349:                /** This represents the 'true' password
0350:                 */
0351:                protected String getUsersPassword() {
0352:                    return "secret";
0353:                }
0354:            }
0355:
0356:            public static class HashTestLoginModule extends TestLoginModule {
0357:                /** This represents the 'true' password in its hashed form
0358:                 */
0359:                protected String getUsersPassword() {
0360:                    MessageDigest md = null;
0361:                    try {
0362:                        md = MessageDigest.getInstance("MD5");
0363:                    } catch (Exception e) {
0364:                        e.printStackTrace();
0365:                    }
0366:                    byte[] passwordBytes = "secret".getBytes();
0367:                    byte[] hash = md.digest(passwordBytes);
0368:                    String passwordHash = Util.encodeBase64(hash);
0369:                    return passwordHash;
0370:                }
0371:            }
0372:
0373:            public static class HashTestDigestCallbackLoginModule extends
0374:                    TestLoginModule {
0375:                /** This represents the 'true' password in its hashed form
0376:                 */
0377:                protected String getUsersPassword() {
0378:                    MessageDigest md = null;
0379:                    try {
0380:                        md = MessageDigest.getInstance("MD5");
0381:                    } catch (Exception e) {
0382:                        e.printStackTrace();
0383:                    }
0384:                    byte[] passwordBytes = "secret".getBytes();
0385:                    md.update("pre".getBytes());
0386:                    md.update(passwordBytes);
0387:                    md.update("post".getBytes());
0388:                    byte[] hash = md.digest();
0389:                    String passwordHash = Util.encodeBase64(hash);
0390:                    return passwordHash;
0391:                }
0392:            }
0393:
0394:            /** A pseudo DataSource that is used to provide Hypersonic db
0395:             connections to the DatabaseServerLoginModule.
0396:             */
0397:            static class TestDS implements  DataSource, Serializable {
0398:                private static final long serialVersionUID = 1;
0399:
0400:                public java.sql.Connection getConnection()
0401:                        throws java.sql.SQLException {
0402:                    return getConnection("sa", "");
0403:                }
0404:
0405:                public java.sql.Connection getConnection(String user,
0406:                        String pass) throws java.sql.SQLException {
0407:                    java.sql.Connection con = null;
0408:                    String jdbcURL = "";
0409:                    try {
0410:                        jdbcURL = "jdbc:hsqldb:hsql://"
0411:                                + System.getProperty("jbosstest.server.host",
0412:                                        "localhost") + ":1701";
0413:                        con = DriverManager.getConnection(jdbcURL, user, pass);
0414:                    } catch (java.sql.SQLException sqle) {
0415:                        jdbcURL = "jdbc:hsqldb:."; // only memory jdbc url
0416:                        con = DriverManager.getConnection(jdbcURL, user, pass);
0417:                    }
0418:                    return con;
0419:                }
0420:
0421:                public java.io.PrintWriter getLogWriter()
0422:                        throws java.sql.SQLException {
0423:                    return null;
0424:                }
0425:
0426:                public void setLogWriter(java.io.PrintWriter out)
0427:                        throws java.sql.SQLException {
0428:                }
0429:
0430:                public int getLoginTimeout() throws java.sql.SQLException {
0431:                    return 0;
0432:                }
0433:
0434:                public void setLoginTimeout(int seconds)
0435:                        throws java.sql.SQLException {
0436:                }
0437:            }
0438:
0439:            static class TestSecurityDomain implements  SecurityDomain,
0440:                    Serializable {
0441:                private static final long serialVersionUID = 1;
0442:
0443:                private transient KeyStore store;
0444:
0445:                public KeyStore getKeyStore() throws SecurityException {
0446:                    return store;
0447:                }
0448:
0449:                public KeyManagerFactory getKeyManagerFactory()
0450:                        throws SecurityException {
0451:                    return null;
0452:                }
0453:
0454:                public KeyStore getTrustStore() throws SecurityException {
0455:                    return store;
0456:                }
0457:
0458:                public TrustManagerFactory getTrustManagerFactory()
0459:                        throws SecurityException {
0460:                    return null;
0461:                }
0462:
0463:                public String getSecurityDomain() {
0464:                    return null;
0465:                }
0466:
0467:                public Subject getActiveSubject() {
0468:                    return null;
0469:                }
0470:
0471:                public boolean isValid(Principal principal, Object credential,
0472:                        Subject activeSubject) {
0473:                    return false;
0474:                }
0475:
0476:                public boolean isValid(Principal principal, Object credential) {
0477:                    return false;
0478:                }
0479:
0480:                public Principal getPrincipal(Principal principal) {
0481:                    return null;
0482:                }
0483:
0484:                public boolean doesUserHaveRole(Principal principal, Set roles) {
0485:                    return false;
0486:                }
0487:
0488:                public Set getUserRoles(Principal principal) {
0489:                    return null;
0490:                }
0491:
0492:                private void readObject(java.io.ObjectInputStream in)
0493:                        throws IOException {
0494:                    try {
0495:                        store = KeyStore.getInstance("JKS");
0496:                        ClassLoader loader = Thread.currentThread()
0497:                                .getContextClassLoader();
0498:                        URL resURL = loader
0499:                                .getResource("security/tst.keystore");
0500:                        store.load(resURL.openStream(), "unit-tests"
0501:                                .toCharArray());
0502:                    } catch (Exception e) {
0503:                        throw new IOException(e.toString());
0504:                    }
0505:                }
0506:            }
0507:
0508:            public LoginModulesUnitTestCase(String testName) {
0509:                super (testName);
0510:            }
0511:
0512:            protected void setUp() throws Exception {
0513:                // Install the custom JAAS configuration
0514:                Configuration.setConfiguration(new TestConfig());
0515:
0516:                // Turn on trace level logging
0517:                Logger root = Logger.getRootLogger();
0518:                root.setLevel(XLevel.TRACE);
0519:            }
0520:
0521:            public void testClientLogin() throws Exception {
0522:                getLog().info("testClientLogin");
0523:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0524:                        "scott", "secret".toCharArray());
0525:                LoginContext lc = new LoginContext("testClientLogin", handler);
0526:                lc.login();
0527:                Subject subject = lc.getSubject();
0528:                Principal scott = new SimplePrincipal("scott");
0529:                assertTrue("Principals contains scott", subject.getPrincipals()
0530:                        .contains(scott));
0531:                Principal saPrincipal = SecurityAssociation.getPrincipal();
0532:                assertTrue("SecurityAssociation.getPrincipal == scott",
0533:                        saPrincipal.equals(scott));
0534:
0535:                UsernamePasswordHandler handler2 = new UsernamePasswordHandler(
0536:                        "scott2", "secret2".toCharArray());
0537:                LoginContext lc2 = new LoginContext("testClientLogin", handler2);
0538:                lc2.login();
0539:                Principal scott2 = new SimplePrincipal("scott2");
0540:                saPrincipal = SecurityAssociation.getPrincipal();
0541:                assertTrue("SecurityAssociation.getPrincipal == scott2",
0542:                        saPrincipal.equals(scott2));
0543:                lc2.logout();
0544:                saPrincipal = SecurityAssociation.getPrincipal();
0545:                assertTrue("SecurityAssociation.getPrincipal == scott",
0546:                        saPrincipal.equals(scott));
0547:
0548:                lc.logout();
0549:            }
0550:
0551:            public void testUsernamePassword() throws Exception {
0552:                getLog().info("testUsernamePassword");
0553:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0554:                        "scott", "secret".toCharArray());
0555:                LoginContext lc = new LoginContext("testUsernamePassword",
0556:                        handler);
0557:                lc.login();
0558:                Subject subject = lc.getSubject();
0559:                Set groups = subject.getPrincipals(Group.class);
0560:                assertTrue("Principals contains scott", subject.getPrincipals()
0561:                        .contains(new SimplePrincipal("scott")));
0562:                assertTrue("Principals contains Roles", groups
0563:                        .contains(new SimplePrincipal("Roles")));
0564:                Group roles = (Group) groups.iterator().next();
0565:                assertTrue("TestRole is a role", roles
0566:                        .isMember(new SimplePrincipal("TestRole")));
0567:                assertTrue("Role2 is a role", roles
0568:                        .isMember(new SimplePrincipal("Role2")));
0569:
0570:                lc.logout();
0571:            }
0572:
0573:            public void testUsernamePasswordHash() throws Exception {
0574:                getLog().info("testUsernamePasswordHash");
0575:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0576:                        "scott", "secret".toCharArray());
0577:                LoginContext lc = new LoginContext("testUsernamePasswordHash",
0578:                        handler);
0579:                lc.login();
0580:                Subject subject = lc.getSubject();
0581:                Set groups = subject.getPrincipals(Group.class);
0582:                assertTrue("Principals contains scott", subject.getPrincipals()
0583:                        .contains(new SimplePrincipal("scott")));
0584:                assertTrue("Principals contains Roles", groups
0585:                        .contains(new SimplePrincipal("Roles")));
0586:                Group roles = (Group) groups.iterator().next();
0587:                assertTrue("TestRole is a role", roles
0588:                        .isMember(new SimplePrincipal("TestRole")));
0589:                assertTrue("Role2 is a role", roles
0590:                        .isMember(new SimplePrincipal("Role2")));
0591:
0592:                lc.logout();
0593:            }
0594:
0595:            public void testUsernamePasswordHashWithDigestCallback()
0596:                    throws Exception {
0597:                getLog().info("testUsernamePasswordHashWithDigestCallback");
0598:                // secret in ascii
0599:                byte[] passBytes = { 115, 101, 99, 114, 101, 116 };
0600:                String pass = new String(passBytes, "UTF-8");
0601:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0602:                        "scott", pass.toCharArray());
0603:                LoginContext lc = new LoginContext(
0604:                        "testUsernamePasswordHashWithDigestCallback", handler);
0605:                lc.login();
0606:                Subject subject = lc.getSubject();
0607:                Set groups = subject.getPrincipals(Group.class);
0608:                assertTrue("Principals contains scott", subject.getPrincipals()
0609:                        .contains(new SimplePrincipal("scott")));
0610:                assertTrue("Principals contains Roles", groups
0611:                        .contains(new SimplePrincipal("Roles")));
0612:                Group roles = (Group) groups.iterator().next();
0613:                assertTrue("TestRole is a role", roles
0614:                        .isMember(new SimplePrincipal("TestRole")));
0615:                assertTrue("Role2 is a role", roles
0616:                        .isMember(new SimplePrincipal("Role2")));
0617:
0618:                lc.logout();
0619:            }
0620:
0621:            public void testUsersRoles() throws Exception {
0622:                getLog().info("testUsersRoles");
0623:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0624:                        "scott", "echoman".toCharArray());
0625:                LoginContext lc = new LoginContext("testUsersRoles", handler);
0626:                lc.login();
0627:                Subject subject = lc.getSubject();
0628:                Set groups = subject.getPrincipals(Group.class);
0629:                assertTrue("Principals contains scott", subject.getPrincipals()
0630:                        .contains(new SimplePrincipal("scott")));
0631:                assertTrue("Principals contains Roles", groups
0632:                        .contains(new SimplePrincipal("Roles")));
0633:                assertTrue("Principals contains CallerPrincipal", groups
0634:                        .contains(new SimplePrincipal("CallerPrincipal")));
0635:                Group roles = (Group) groups.iterator().next();
0636:                Iterator groupsIter = groups.iterator();
0637:                while (groupsIter.hasNext()) {
0638:                    roles = (Group) groupsIter.next();
0639:                    if (roles.getName().equals("Roles")) {
0640:                        assertTrue("Echo is a role", roles
0641:                                .isMember(new SimplePrincipal("Echo")));
0642:                        assertTrue("Java is NOT a role", roles
0643:                                .isMember(new SimplePrincipal("Java")) == false);
0644:                        assertTrue(
0645:                                "Coder is NOT a role",
0646:                                roles.isMember(new SimplePrincipal("Coder")) == false);
0647:                    } else if (roles.getName().equals("CallerPrincipal")) {
0648:                        getLog().info(
0649:                                "CallerPrincipal is "
0650:                                        + roles.members().nextElement());
0651:                        boolean isMember = roles.isMember(new SimplePrincipal(
0652:                                "callerScott"));
0653:                        assertTrue("CallerPrincipal is callerScott", isMember);
0654:                    }
0655:                }
0656:                lc.logout();
0657:
0658:                handler = new UsernamePasswordHandler("stark", "javaman"
0659:                        .toCharArray());
0660:                lc = new LoginContext("testUsersRoles", handler);
0661:                lc.login();
0662:                subject = lc.getSubject();
0663:                groups = subject.getPrincipals(Group.class);
0664:                assertTrue("Principals contains stark", subject.getPrincipals()
0665:                        .contains(new SimplePrincipal("stark")));
0666:                assertTrue("Principals contains Roles", groups
0667:                        .contains(new SimplePrincipal("Roles")));
0668:                assertTrue("Principals contains CallerPrincipal", groups
0669:                        .contains(new SimplePrincipal("CallerPrincipal")));
0670:                groupsIter = groups.iterator();
0671:                while (groupsIter.hasNext()) {
0672:                    roles = (Group) groupsIter.next();
0673:                    if (roles.getName().equals("Roles")) {
0674:                        assertTrue("Echo is NOT a role", roles
0675:                                .isMember(new SimplePrincipal("Echo")) == false);
0676:                        assertTrue("Java is a role", roles
0677:                                .isMember(new SimplePrincipal("Java")));
0678:                        assertTrue("Coder is a role", roles
0679:                                .isMember(new SimplePrincipal("Coder")));
0680:                    } else if (roles.getName().equals("CallerPrincipal")) {
0681:                        getLog().info(
0682:                                "CallerPrincipal is "
0683:                                        + roles.members().nextElement());
0684:                        boolean isMember = roles.isMember(new SimplePrincipal(
0685:                                "callerStark"));
0686:                        assertTrue("CallerPrincipal is callerStark", isMember);
0687:                    }
0688:                }
0689:                lc.logout();
0690:
0691:                // Test the usernames with common prefix
0692:                getLog().info("Testing similar usernames");
0693:                handler = new UsernamePasswordHandler("jdukeman", "anotherduke"
0694:                        .toCharArray());
0695:                lc = new LoginContext("testUsersRoles", handler);
0696:                lc.login();
0697:                subject = lc.getSubject();
0698:                groups = subject.getPrincipals(Group.class);
0699:                assertTrue("Principals contains jdukeman", subject
0700:                        .getPrincipals().contains(
0701:                                new SimplePrincipal("jdukeman")));
0702:                assertTrue("Principals contains Roles", groups
0703:                        .contains(new SimplePrincipal("Roles")));
0704:                assertTrue("Principals contains CallerPrincipal", groups
0705:                        .contains(new SimplePrincipal("CallerPrincipal")));
0706:                groupsIter = groups.iterator();
0707:                while (groupsIter.hasNext()) {
0708:                    roles = (Group) groupsIter.next();
0709:                    if (roles.getName().equals("Roles")) {
0710:                        assertTrue(
0711:                                "Role1 is NOT a role",
0712:                                roles.isMember(new SimplePrincipal("Role1")) == false);
0713:                        assertTrue("Role2 is a role", roles
0714:                                .isMember(new SimplePrincipal("Role2")));
0715:                        assertTrue("Role3 is a role", roles
0716:                                .isMember(new SimplePrincipal("Role3")));
0717:                    } else if (roles.getName().equals("CallerPrincipal")) {
0718:                        getLog().info(
0719:                                "CallerPrincipal is "
0720:                                        + roles.members().nextElement());
0721:                        boolean isMember = roles.isMember(new SimplePrincipal(
0722:                                "callerJdukeman"));
0723:                        assertTrue("CallerPrincipal is callerJdukeman",
0724:                                isMember);
0725:                    }
0726:                }
0727:                lc.logout();
0728:            }
0729:
0730:            public void testUsersRolesHash() throws Exception {
0731:                getLog().info("testUsersRolesHash");
0732:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0733:                        "scott", "echoman".toCharArray());
0734:                LoginContext lc = new LoginContext("testUsersRolesHash",
0735:                        handler);
0736:                lc.login();
0737:                Subject subject = lc.getSubject();
0738:                Set groups = subject.getPrincipals(Group.class);
0739:                assertTrue("Principals contains scott", subject.getPrincipals()
0740:                        .contains(new SimplePrincipal("scott")));
0741:                assertTrue("Principals contains Roles", groups
0742:                        .contains(new SimplePrincipal("Roles")));
0743:                assertTrue("Principals contains CallerPrincipal", groups
0744:                        .contains(new SimplePrincipal("CallerPrincipal")));
0745:                Group roles = (Group) groups.iterator().next();
0746:                Iterator groupsIter = groups.iterator();
0747:                while (groupsIter.hasNext()) {
0748:                    roles = (Group) groupsIter.next();
0749:                    if (roles.getName().equals("Roles")) {
0750:                        assertTrue("Echo is a role", roles
0751:                                .isMember(new SimplePrincipal("Echo")));
0752:                        assertTrue("Java is NOT a role", roles
0753:                                .isMember(new SimplePrincipal("Java")) == false);
0754:                        assertTrue(
0755:                                "Coder is NOT a role",
0756:                                roles.isMember(new SimplePrincipal("Coder")) == false);
0757:                    } else if (roles.getName().equals("CallerPrincipal")) {
0758:                        getLog().info(
0759:                                "CallerPrincipal is "
0760:                                        + roles.members().nextElement());
0761:                        boolean isMember = roles.isMember(new SimplePrincipal(
0762:                                "callerScott"));
0763:                        assertTrue("CallerPrincipal is callerScott", isMember);
0764:                    }
0765:                }
0766:                lc.logout();
0767:            }
0768:
0769:            public void testAnonUsersRoles() throws Exception {
0770:                getLog().info("testAnonUsersRoles");
0771:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0772:                        null, null);
0773:                LoginContext lc = new LoginContext("testAnonUsersRoles",
0774:                        handler);
0775:                lc.login();
0776:                Subject subject = lc.getSubject();
0777:                Set groups = subject.getPrincipals(Group.class);
0778:                assertTrue("Principals contains nobody", subject
0779:                        .getPrincipals()
0780:                        .contains(new SimplePrincipal("nobody")));
0781:                assertTrue("Principals contains Roles", groups
0782:                        .contains(new SimplePrincipal("Roles")));
0783:                Group roles = (Group) groups.iterator().next();
0784:                assertTrue("Roles has no members", roles.members()
0785:                        .hasMoreElements() == false);
0786:
0787:                lc.logout();
0788:            }
0789:
0790:            public void testAnon() throws Exception {
0791:                getLog().info("testAnon");
0792:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0793:                        null, null);
0794:                LoginContext lc = new LoginContext("testAnon", handler);
0795:                lc.login();
0796:                Subject subject = lc.getSubject();
0797:                Set groups = subject.getPrincipals(Group.class);
0798:                assertTrue("Principals contains nobody", subject
0799:                        .getPrincipals()
0800:                        .contains(new SimplePrincipal("nobody")));
0801:                assertTrue("Principals contains Roles", groups
0802:                        .contains(new SimplePrincipal("Roles")));
0803:                Group roles = (Group) groups.iterator().next();
0804:                assertTrue("Roles has no members", roles.members()
0805:                        .hasMoreElements() == false);
0806:
0807:                lc.logout();
0808:            }
0809:
0810:            public void testNull() throws Exception {
0811:                getLog().info("testNull");
0812:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0813:                        null, null);
0814:                LoginContext lc = new LoginContext("testNull", handler);
0815:                try {
0816:                    lc.login();
0817:                    fail("Should not be able to login as null, null");
0818:                } catch (LoginException e) {
0819:                    // Ok
0820:                }
0821:            }
0822:
0823:            public void testIdentity() throws Exception {
0824:                getLog().info("testIdentity");
0825:                LoginContext lc = new LoginContext("testIdentity");
0826:                lc.login();
0827:                Subject subject = lc.getSubject();
0828:                Set groups = subject.getPrincipals(Group.class);
0829:                assertTrue("Principals contains stark", subject.getPrincipals()
0830:                        .contains(new SimplePrincipal("stark")));
0831:                assertTrue("Principals contains Roles", groups
0832:                        .contains(new SimplePrincipal("Roles")));
0833:                Group roles = (Group) groups.iterator().next();
0834:                assertTrue("Role2 is not a role", roles
0835:                        .isMember(new SimplePrincipal("Role2")) == false);
0836:                assertTrue("Role3 is a role", roles
0837:                        .isMember(new SimplePrincipal("Role3")));
0838:                assertTrue("Role4 is a role", roles
0839:                        .isMember(new SimplePrincipal("Role4")));
0840:
0841:                lc.logout();
0842:            }
0843:
0844:            public void testJCACallerIdentity() throws Exception {
0845:                log.info("testJCACallerIdentity");
0846:                MBeanServer server = MBeanServerFactory
0847:                        .createMBeanServer("jboss");
0848:                LoginContext lc = new LoginContext("testJCACallerIdentity");
0849:                lc.login();
0850:                Subject subject = lc.getSubject();
0851:                assertTrue("Principals contains jduke", subject.getPrincipals()
0852:                        .contains(new SimplePrincipal("jduke")));
0853:                Set creds = subject
0854:                        .getPrivateCredentials(PasswordCredential.class);
0855:                PasswordCredential pc = (PasswordCredential) creds.iterator()
0856:                        .next();
0857:                String username = pc.getUserName();
0858:                String password = new String(pc.getPassword());
0859:                assertTrue("PasswordCredential.username = jduke", username
0860:                        .equals("jduke"));
0861:                assertTrue("PasswordCredential.password = theduke", password
0862:                        .equals("theduke"));
0863:                lc.logout();
0864:
0865:                // Test the override of the default identity
0866:                SecurityAssociation.setPrincipal(new SimplePrincipal("jduke2"));
0867:                SecurityAssociation.setCredential("theduke2".toCharArray());
0868:                lc.login();
0869:                subject = lc.getSubject();
0870:                Set principals = subject.getPrincipals();
0871:                assertTrue("Principals contains jduke2", principals
0872:                        .contains(new SimplePrincipal("jduke2")));
0873:                assertTrue("Principals does not contains jduke", principals
0874:                        .contains(new SimplePrincipal("jduke")) == false);
0875:                creds = subject.getPrivateCredentials(PasswordCredential.class);
0876:                pc = (PasswordCredential) creds.iterator().next();
0877:                username = pc.getUserName();
0878:                password = new String(pc.getPassword());
0879:                assertTrue("PasswordCredential.username = jduke2", username
0880:                        .equals("jduke2"));
0881:                assertTrue("PasswordCredential.password = theduke2", password
0882:                        .equals("theduke2"));
0883:                lc.logout();
0884:                MBeanServerFactory.releaseMBeanServer(server);
0885:            }
0886:
0887:            public void testJaasSecurityDomainIdentityLoginModule()
0888:                    throws Exception {
0889:                log.info("testJaasSecurityDomainIdentityLoginModule");
0890:                MBeanServer server = MBeanServerFactory
0891:                        .createMBeanServer("jboss");
0892:                JaasSecurityDomain secDomain = new JaasSecurityDomain(
0893:                        "testEncodeDecode");
0894:                secDomain.setSalt("abcdefgh");
0895:                secDomain.setIterationCount(13);
0896:                secDomain.setKeyStorePass("master");
0897:                secDomain.setManagerServiceName(null);
0898:                secDomain.start();
0899:                ObjectName name = new ObjectName(
0900:                        "jboss.test:service=JaasSecurityDomain,domain=testJaasSecurityDomainIdentityLoginModule");
0901:                server.registerMBean(secDomain, name);
0902:
0903:                LoginContext lc = new LoginContext(
0904:                        "testJaasSecurityDomainIdentityLoginModule");
0905:                lc.login();
0906:                Subject subject = lc.getSubject();
0907:                assertTrue("Principals contains sa", subject.getPrincipals()
0908:                        .contains(new SimplePrincipal("sa")));
0909:                Set creds = subject
0910:                        .getPrivateCredentials(PasswordCredential.class);
0911:                PasswordCredential pc = (PasswordCredential) creds.iterator()
0912:                        .next();
0913:                String username = pc.getUserName();
0914:                String password = new String(pc.getPassword());
0915:                assertTrue("PasswordCredential.username = sa", username
0916:                        .equals("sa"));
0917:                assertTrue("PasswordCredential.password = ", password
0918:                        .equals(""));
0919:                lc.logout();
0920:                server.unregisterMBean(name);
0921:                MBeanServerFactory.releaseMBeanServer(server);
0922:            }
0923:
0924:            public void testSimple() throws Exception {
0925:                getLog().info("testSimple");
0926:                UsernamePasswordHandler handler = new UsernamePasswordHandler(
0927:                        "jduke", "jduke".toCharArray());
0928:                LoginContext lc = new LoginContext("testSimple", handler);
0929:                lc.login();
0930:                Subject subject = lc.getSubject();
0931:                Set groups = subject.getPrincipals(Group.class);
0932:                assertTrue("Principals contains jduke", subject.getPrincipals()
0933:                        .contains(new SimplePrincipal("jduke")));
0934:                assertTrue("Principals contains Roles", groups
0935:                        .contains(new SimplePrincipal("Roles")));
0936:                Group roles = (Group) groups.iterator().next();
0937:                assertTrue("user is a role", roles
0938:                        .isMember(new SimplePrincipal("user")));
0939:                assertTrue("guest is a role", roles
0940:                        .isMember(new SimplePrincipal("guest")));
0941:
0942:                lc.logout();
0943:            }
0944:
0945:            /** Use this DDL script to setup tables:
0946:             ; First load the JDBC driver and open a database.
0947:             d org.enhydra.instantdb.jdbc.idbDriver;
0948:             o jdbc:idb=/usr/local/src/cvsroot/jBoss/jboss/dist/conf/default/instantdb.properties;
0949:
0950:             ; Create the Principal table
0951:             e DROP TABLE Principals ;
0952:             e CREATE TABLE Principals (
0953:             PrincipalID	VARCHAR(64) PRIMARY KEY,
0954:             Password	VARCHAR(64) );
0955:
0956:             ; put some initial data in the table
0957:             e INSERT INTO Principals VALUES ("scott", "echoman");
0958:             e INSERT INTO Principals VALUES ("stark", "javaman");
0959:
0960:             ; Create the Roles table
0961:             e DROP TABLE Roles;
0962:             e CREATE TABLE Roles (
0963:             PrincipalID	VARCHAR(64) PRIMARY KEY,
0964:             Role	VARCHAR(64),
0965:             RoleGroup VARCHAR(64) );
0966:
0967:             ; put some initial data in the table
0968:             e INSERT INTO Roles VALUES ("scott", "Echo", "");
0969:             e INSERT INTO Roles VALUES ("scott", "caller_scott", "CallerPrincipal");
0970:             e INSERT INTO Roles VALUES ("stark", "Java", "");
0971:             e INSERT INTO Roles VALUES ("stark", "Coder", "");
0972:             e INSERT INTO Roles VALUES ("stark", "caller_stark", "CallerPrincipal");
0973:
0974:             c close;
0975:             */
0976:            public void testJdbc() throws Exception {
0977:                getLog().info("testJdbc");
0978:
0979:                Connection conn = setupLoginTables();
0980:                try {
0981:                    UsernamePasswordHandler handler = new UsernamePasswordHandler(
0982:                            "stark", "javaman".toCharArray());
0983:                    LoginContext lc = new LoginContext("testJdbc", handler);
0984:                    lc.login();
0985:                    Subject subject = lc.getSubject();
0986:                    Set groups = subject.getPrincipals(Group.class);
0987:                    assertTrue("Principals contains stark", subject
0988:                            .getPrincipals().contains(
0989:                                    new SimplePrincipal("stark")));
0990:                    assertTrue("Principals contains Roles", groups
0991:                            .contains(new SimplePrincipal("Roles")));
0992:                    Group roles = (Group) groups.iterator().next();
0993:                    assertTrue("Java is a role", roles
0994:                            .isMember(new SimplePrincipal("Java")));
0995:                    assertTrue("Coder is a role", roles
0996:                            .isMember(new SimplePrincipal("Coder")));
0997:
0998:                    lc.logout();
0999:                } finally {
1000:                    conn.close();
1001:                }
1002:            }
1003:
1004:            public void testControlFlags() throws Exception {
1005:                getLog().info("testControlFlags");
1006:
1007:                Connection conn = setupLoginTables();
1008:                try {
1009:                    Configuration cfg = Configuration.getConfiguration();
1010:                    AppConfigurationEntry[] ace = cfg
1011:                            .getAppConfigurationEntry("testControlFlags");
1012:                    for (int n = 0; n < ace.length; n++) {
1013:                        assertTrue(
1014:                                "testControlFlags flag==SUFFICIENT",
1015:                                ace[n].getControlFlag() == AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT);
1016:                        getLog().info(ace[n].getControlFlag());
1017:                    }
1018:
1019:                    /* Test that the UsersRolesLoginModule is sufficient to login. Only the
1020:                     users.properties file has a jduke=theduke username to password mapping,
1021:                     and the DatabaseServerLoginModule will fail.
1022:                     */
1023:                    UsernamePasswordHandler handler = new UsernamePasswordHandler(
1024:                            "jduke", "theduke".toCharArray());
1025:                    LoginContext lc = new LoginContext("testControlFlags",
1026:                            handler);
1027:                    lc.login();
1028:                    Subject subject = lc.getSubject();
1029:                    Set groups = subject.getPrincipals(Group.class);
1030:                    assertTrue("Principals contains jduke", subject
1031:                            .getPrincipals().contains(
1032:                                    new SimplePrincipal("jduke")));
1033:                    assertTrue("Principals contains Roles", groups
1034:                            .contains(new SimplePrincipal("Roles")));
1035:                    Group roles = (Group) groups.iterator().next();
1036:                    // Only the roles from the DatabaseServerLoginModule should exist
1037:                    assertTrue("Role1 is a role", roles
1038:                            .isMember(new SimplePrincipal("Role1")));
1039:                    assertTrue("Role2 is a role", roles
1040:                            .isMember(new SimplePrincipal("Role2")));
1041:                    assertTrue("Role3 is NOT a role", !roles
1042:                            .isMember(new SimplePrincipal("Role3")));
1043:                    assertTrue("Role4 is NOT a role", !roles
1044:                            .isMember(new SimplePrincipal("Role4")));
1045:                    lc.logout();
1046:
1047:                    /* Test that the DatabaseServerLoginModule is sufficient to login. Only the
1048:                      Principals table has a jduke=jduke username to password mapping, and
1049:                      the UsersRolesLoginModule will fail.
1050:                     */
1051:                    handler = new UsernamePasswordHandler("jduke", "jduke"
1052:                            .toCharArray());
1053:                    lc = new LoginContext("testControlFlags", handler);
1054:                    lc.login();
1055:                    subject = lc.getSubject();
1056:                    groups = subject.getPrincipals(Group.class);
1057:                    assertTrue("Principals contains jduke", subject
1058:                            .getPrincipals().contains(
1059:                                    new SimplePrincipal("jduke")));
1060:                    assertTrue("Principals contains Roles", groups
1061:                            .contains(new SimplePrincipal("Roles")));
1062:                    roles = (Group) groups.iterator().next();
1063:                    Enumeration iter = roles.members();
1064:                    while (iter.hasMoreElements())
1065:                        getLog().debug(iter.nextElement());
1066:                    // Only the roles from the DatabaseServerLoginModule should exist
1067:                    assertTrue("Role1 is NOT a role", !roles
1068:                            .isMember(new SimplePrincipal("Role1")));
1069:                    assertTrue("Role2 is NOT a role", !roles
1070:                            .isMember(new SimplePrincipal("Role2")));
1071:                    assertTrue("Role3 is a role", roles
1072:                            .isMember(new SimplePrincipal("Role3")));
1073:                    assertTrue("Role4 is a role", roles
1074:                            .isMember(new SimplePrincipal("Role4")));
1075:                    lc.logout();
1076:                } finally {
1077:                    conn.close();
1078:                }
1079:            }
1080:
1081:            public void testCertLogin() throws Exception {
1082:                getLog().info("testCertLogin");
1083:                InitialContext ctx = new InitialContext();
1084:                ctx.rebind("testCertLogin", new TestSecurityDomain());
1085:
1086:                KeyStore store = KeyStore.getInstance("JKS");
1087:                ClassLoader loader = Thread.currentThread()
1088:                        .getContextClassLoader();
1089:                URL resURL = loader.getResource("security/tst.keystore");
1090:                store.load(resURL.openStream(), "unit-tests".toCharArray());
1091:                X509Certificate cert = (X509Certificate) store
1092:                        .getCertificate("unit-tests");
1093:                SimplePrincipal x509 = new SimplePrincipal("unit-tests");
1094:                SecurityAssociationHandler handler = new SecurityAssociationHandler(
1095:                        x509, cert);
1096:                LoginContext lc = new LoginContext("testCertLogin", handler);
1097:                lc.login();
1098:                Subject subject = lc.getSubject();
1099:                assertTrue("Principals contains unit-tests", subject
1100:                        .getPrincipals().contains(
1101:                                new SimplePrincipal("unit-tests")));
1102:                assertTrue("Principals contains x509cert", subject
1103:                        .getPublicCredentials().contains(cert));
1104:            }
1105:
1106:            public void testCertRoles() throws Exception {
1107:                getLog().info("testCertRoles");
1108:                InitialContext ctx = new InitialContext();
1109:                ctx.rebind("testCertRoles", new TestSecurityDomain());
1110:
1111:                KeyStore store = KeyStore.getInstance("JKS");
1112:                ClassLoader loader = Thread.currentThread()
1113:                        .getContextClassLoader();
1114:                URL resURL = loader.getResource("security/tst.keystore");
1115:                store.load(resURL.openStream(), "unit-tests".toCharArray());
1116:                X509Certificate cert = (X509Certificate) store
1117:                        .getCertificate("unit-tests");
1118:                SimplePrincipal x509 = new SimplePrincipal("unit-tests");
1119:                SecurityAssociationHandler handler = new SecurityAssociationHandler(
1120:                        x509, cert);
1121:                LoginContext lc = new LoginContext("testCertRoles", handler);
1122:                lc.login();
1123:                Subject subject = lc.getSubject();
1124:                Set groups = subject.getPrincipals(Group.class);
1125:                assertTrue("Principals contains unit-tests", subject
1126:                        .getPrincipals().contains(
1127:                                new SimplePrincipal("unit-tests")));
1128:                assertTrue("Principals contains Roles", groups
1129:                        .contains(new SimplePrincipal("Roles")));
1130:                assertTrue("Principals contains x509cert", subject
1131:                        .getPublicCredentials().contains(cert));
1132:                Group roles = (Group) groups.iterator().next();
1133:                Iterator groupsIter = groups.iterator();
1134:                while (groupsIter.hasNext()) {
1135:                    roles = (Group) groupsIter.next();
1136:                    if (roles.getName().equals("Roles")) {
1137:                        assertTrue("CertUser is a role", roles
1138:                                .isMember(new SimplePrincipal("CertUser")));
1139:                        assertTrue("Java is NOT a role", roles
1140:                                .isMember(new SimplePrincipal("Java")) == false);
1141:                        assertTrue(
1142:                                "Coder is NOT a role",
1143:                                roles.isMember(new SimplePrincipal("Coder")) == false);
1144:                    } else if (roles.getName().equals("CallerPrincipal")) {
1145:                        getLog().info(
1146:                                "CallerPrincipal is "
1147:                                        + roles.members().nextElement());
1148:                        boolean isMember = roles.isMember(new SimplePrincipal(
1149:                                "callerX509"));
1150:                        assertTrue("CallerPrincipal is callerX509", isMember);
1151:                    }
1152:                }
1153:                lc.logout();
1154:
1155:            }
1156:
1157:            private Connection setupLoginTables() throws Exception {
1158:                Class.forName("org.hsqldb.jdbcDriver");
1159:                // Create a DataSource binding
1160:                TestDS ds = new TestDS();
1161:                InitialContext ctx = new InitialContext();
1162:                ctx.rebind("testJdbc", ds);
1163:
1164:                // Start database and setup tables
1165:                Connection conn = ds.getConnection("sa", "");
1166:                Statement statement = conn.createStatement();
1167:                createPrincipalsTable(statement);
1168:                createRolesTable(statement);
1169:                statement.close();
1170:
1171:                // no connection closing, if hsql is in process
1172:                // the database is disposed
1173:                return conn;
1174:            }
1175:
1176:            private void createPrincipalsTable(Statement statement)
1177:                    throws SQLException {
1178:                try {
1179:                    statement.execute("DROP TABLE Principals");
1180:                } catch (SQLException e) {
1181:                    // Ok, assume table does not exist
1182:                }
1183:                boolean result = statement.execute("CREATE TABLE Principals ("
1184:                        + "PrincipalID VARCHAR(64) PRIMARY KEY,"
1185:                        + "Password VARCHAR(64) )");
1186:                getLog().info("Created Principals table, result=" + result);
1187:                result = statement
1188:                        .execute("INSERT INTO Principals VALUES ('scott', 'echoman')");
1189:                getLog().info(
1190:                        "INSERT INTO Principals VALUES ('scott', 'echoman'), result="
1191:                                + result);
1192:                result = statement
1193:                        .execute("INSERT INTO Principals VALUES ('stark', 'javaman')");
1194:                getLog().info(
1195:                        "INSERT INTO Principals VALUES ('stark', 'javaman'), result="
1196:                                + result);
1197:                // This differs from the users.properties jduke settings
1198:                result = statement
1199:                        .execute("INSERT INTO Principals VALUES ('jduke', 'jduke')");
1200:                getLog().info(
1201:                        "INSERT INTO Principals VALUES ('jduke', 'jduke'), result="
1202:                                + result);
1203:            }
1204:
1205:            private void createRolesTable(Statement statement)
1206:                    throws SQLException {
1207:                try {
1208:                    statement.execute("DROP TABLE Roles");
1209:                } catch (SQLException e) {
1210:                    // Ok, assume table does not exist
1211:                }
1212:                boolean result = statement.execute("CREATE TABLE Roles ("
1213:                        + "PrincipalID	VARCHAR(64)," + "Role	VARCHAR(64),"
1214:                        + "RoleGroup VARCHAR(64) )");
1215:                getLog().info("Created Roles table, result=" + result);
1216:                result = statement
1217:                        .execute("INSERT INTO Roles VALUES ('scott', 'Echo', 'Roles')");
1218:                getLog().info(
1219:                        "INSERT INTO Roles VALUES ('scott', 'Echo', 'Roles'), result="
1220:                                + result);
1221:                result = statement
1222:                        .execute("INSERT INTO Roles VALUES ('scott', 'callerScott', 'CallerPrincipal')");
1223:                getLog().info(
1224:                        "INSERT INTO Roles VALUES ('scott', 'callerScott', 'CallerPrincipal'), result="
1225:                                + result);
1226:                result = statement
1227:                        .execute("INSERT INTO Roles VALUES ('stark', 'Java', 'Roles')");
1228:                getLog().info(
1229:                        "INSERT INTO Roles VALUES ('stark', 'Java', 'Roles'), result="
1230:                                + result);
1231:                result = statement
1232:                        .execute("INSERT INTO Roles VALUES ('stark', 'Coder', 'Roles')");
1233:                getLog().info(
1234:                        "INSERT INTO Roles VALUES ('stark', 'Coder', 'Roles'), result="
1235:                                + result);
1236:                result = statement
1237:                        .execute("INSERT INTO Roles VALUES ('stark', 'callerStark', 'CallerPrincipal')");
1238:                getLog().info(
1239:                        "INSERT INTO Roles VALUES ('stark', 'callerStark', 'CallerPrincipal'), result="
1240:                                + result);
1241:                result = statement
1242:                        .execute("INSERT INTO Roles VALUES ('jduke', 'Role3', 'Roles')");
1243:                getLog().info(
1244:                        "INSERT INTO Roles VALUES ('jduke', 'Role3', 'Roles'), result="
1245:                                + result);
1246:                result = statement
1247:                        .execute("INSERT INTO Roles VALUES ('jduke', 'Role4', 'Roles')");
1248:                getLog().info(
1249:                        "INSERT INTO Roles VALUES ('jduke', 'Role4', 'Roles'), result="
1250:                                + result);
1251:            }
1252:
1253:            public static void main(java.lang.String[] args) {
1254:                // Print the location of the users.properties resource
1255:                java.net.URL users = LoginModulesUnitTestCase.class
1256:                        .getResource("/users.properties");
1257:                System.out.println("users.properties is here: " + users);
1258:                TestSuite suite = new TestSuite(LoginModulesUnitTestCase.class);
1259:                junit.textui.TestRunner.run(suite);
1260:            }
1261:
1262:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.