Source Code Cross Referenced for JAASMemoryLoginModule.java in  » Sevlet-Container » tomcat-catalina » org » apache » catalina » realm » 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 » Sevlet Container » tomcat catalina » org.apache.catalina.realm 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright 1999,2004 The Apache Software Foundation.
003:         * 
004:         * Licensed under the Apache License, Version 2.0 (the "License");
005:         * you may not use this file except in compliance with the License.
006:         * You may obtain a copy of the License at
007:         * 
008:         *      http://www.apache.org/licenses/LICENSE-2.0
009:         * 
010:         * Unless required by applicable law or agreed to in writing, software
011:         * distributed under the License is distributed on an "AS IS" BASIS,
012:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013:         * See the License for the specific language governing permissions and
014:         * limitations under the License.
015:         */
016:
017:        package org.apache.catalina.realm;
018:
019:        import java.io.File;
020:        import java.io.IOException;
021:        import java.security.Principal;
022:        import java.util.ArrayList;
023:        import java.util.HashMap;
024:        import java.util.Map;
025:
026:        import javax.security.auth.Subject;
027:        import javax.security.auth.callback.Callback;
028:        import javax.security.auth.callback.CallbackHandler;
029:        import javax.security.auth.callback.NameCallback;
030:        import javax.security.auth.callback.PasswordCallback;
031:        import javax.security.auth.callback.UnsupportedCallbackException;
032:        import javax.security.auth.login.FailedLoginException;
033:        import javax.security.auth.login.LoginException;
034:        import javax.security.auth.spi.LoginModule;
035:        import javax.servlet.http.HttpServletRequest;
036:
037:        import org.apache.catalina.Context;
038:        import org.apache.catalina.HttpRequest;
039:        import org.apache.catalina.Realm;
040:        import org.apache.catalina.deploy.SecurityConstraint;
041:        import org.apache.catalina.util.RequestUtil;
042:        import org.apache.catalina.util.StringManager;
043:        import org.apache.commons.digester.Digester;
044:        import org.apache.commons.logging.Log;
045:        import org.apache.commons.logging.LogFactory;
046:
047:        /**
048:         * <p>Implementation of the JAAS <strong>LoginModule</strong> interface,
049:         * primarily for use in testing <code>JAASRealm</code>.  It utilizes an
050:         * XML-format data file of username/password/role information identical to
051:         * that supported by <code>org.apache.catalina.realm.MemoryRealm</code>
052:         * (except that digested passwords are not supported).</p>
053:         *
054:         * <p>This class recognizes the following string-valued options, which are
055:         * specified in the configuration file (and passed to our constructor in
056:         * the <code>options</code> argument:</p>
057:         * <ul>
058:         * <li><strong>debug</strong> - Set to "true" to get debugging messages
059:         *     generated to System.out.  The default value is <code>false</code>.</li>
060:         * <li><strong>pathname</strong> - Relative (to the pathname specified by the
061:         *     "catalina.base" system property) or absolute pahtname to the
062:         *     XML file containing our user information, in the format supported by
063:         *     {@link MemoryRealm}.  The default value matches the MemoryRealm
064:         *     default.</li>
065:         * </ul>
066:         *
067:         * <p><strong>IMPLEMENTATION NOTE</strong> - This class implements
068:         * <code>Realm</code> only to satisfy the calling requirements of the
069:         * <code>GenericPrincipal</code> constructor.  It does not actually perform
070:         * the functionality required of a <code>Realm</code> implementation.</p>
071:         *
072:         * @author Craig R. McClanahan
073:         * @version $Revision: 1.7 $ $Date: 2004/02/27 14:58:45 $
074:         */
075:
076:        public class JAASMemoryLoginModule extends MemoryRealm implements 
077:                LoginModule, Realm {
078:            // We need to extend MemoryRealm to avoid class cast
079:
080:            private static Log log = LogFactory
081:                    .getLog(JAASMemoryLoginModule.class);
082:
083:            // ----------------------------------------------------- Instance Variables
084:
085:            /**
086:             * The callback handler responsible for answering our requests.
087:             */
088:            protected CallbackHandler callbackHandler = null;
089:
090:            /**
091:             * Has our own <code>commit()</code> returned successfully?
092:             */
093:            protected boolean committed = false;
094:
095:            /**
096:             * Should we log debugging messages?
097:             */
098:            protected boolean debug = false;
099:
100:            /**
101:             * The configuration information for this <code>LoginModule</code>.
102:             */
103:            protected Map options = null;
104:
105:            /**
106:             * The absolute or relative pathname to the XML configuration file.
107:             */
108:            protected String pathname = "conf/tomcat-users.xml";
109:
110:            /**
111:             * The <code>Principal</code> identified by our validation, or
112:             * <code>null</code> if validation falied.
113:             */
114:            protected Principal principal = null;
115:
116:            /**
117:             * The set of <code>Principals</code> loaded from our configuration file.
118:             */
119:            protected HashMap principals = new HashMap();
120:
121:            /**
122:             * The string manager for this package.
123:             */
124:            protected static StringManager sm = StringManager
125:                    .getManager(Constants.Package);
126:
127:            /**
128:             * The state information that is shared with other configured
129:             * <code>LoginModule</code> instances.
130:             */
131:            protected Map sharedState = null;
132:
133:            /**
134:             * The subject for which we are performing authentication.
135:             */
136:            protected Subject subject = null;
137:
138:            // --------------------------------------------------------- Public Methods
139:
140:            public JAASMemoryLoginModule() {
141:                log.debug("MEMORY LOGIN MODULE");
142:            }
143:
144:            /**
145:             * Phase 2 of authenticating a <code>Subject</code> when Phase 1
146:             * fails.  This method is called if the <code>LoginContext</code>
147:             * failed somewhere in the overall authentication chain.
148:             *
149:             * @return <code>true</code> if this method succeeded, or
150:             *  <code>false</code> if this <code>LoginModule</code> should be
151:             *  ignored
152:             *
153:             * @exception LoginException if the abort fails
154:             */
155:            public boolean abort() throws LoginException {
156:
157:                // If our authentication was not successful, just return false
158:                if (principal == null)
159:                    return (false);
160:
161:                // Clean up if overall authentication failed
162:                if (committed)
163:                    logout();
164:                else {
165:                    committed = false;
166:                    principal = null;
167:                }
168:                log.debug("Abort");
169:                return (true);
170:
171:            }
172:
173:            /**
174:             * Phase 2 of authenticating a <code>Subject</code> when Phase 1
175:             * was successful.  This method is called if the <code>LoginContext</code>
176:             * succeeded in the overall authentication chain.
177:             *
178:             * @return <code>true</code> if the authentication succeeded, or
179:             *  <code>false</code> if this <code>LoginModule</code> should be
180:             *  ignored
181:             *
182:             * @exception LoginException if the commit fails
183:             */
184:            public boolean commit() throws LoginException {
185:                log.debug("commit " + principal);
186:
187:                // If authentication was not successful, just return false
188:                if (principal == null)
189:                    return (false);
190:
191:                // Add our Principal to the Subject if needed
192:                if (!subject.getPrincipals().contains(principal))
193:                    subject.getPrincipals().add(principal);
194:
195:                committed = true;
196:                return (true);
197:
198:            }
199:
200:            /**
201:             * Return the SecurityConstraints configured to guard the request URI for
202:             * this request, or <code>null</code> if there is no such constraint.
203:             *
204:             * @param request Request we are processing
205:             * @param context Context the Request is mapped to
206:             */
207:            public SecurityConstraint[] findSecurityConstraints(
208:                    HttpRequest request, Context context) {
209:                ArrayList results = null;
210:                // Are there any defined security constraints?
211:                SecurityConstraint constraints[] = context.findConstraints();
212:                if ((constraints == null) || (constraints.length == 0)) {
213:                    if (debug)
214:                        log("  No applicable constraints defined");
215:                    return (null);
216:                }
217:
218:                // Check each defined security constraint
219:                HttpServletRequest hreq = (HttpServletRequest) request
220:                        .getRequest();
221:                String uri = request.getDecodedRequestURI();
222:                String contextPath = hreq.getContextPath();
223:                if (contextPath.length() > 0)
224:                    uri = uri.substring(contextPath.length());
225:                uri = RequestUtil.URLDecode(uri); // Before checking constraints
226:                String method = hreq.getMethod();
227:                for (int i = 0; i < constraints.length; i++) {
228:                    if (debug)
229:                        log("  Checking constraint '" + constraints[i]
230:                                + "' against " + method + " " + uri + " --> "
231:                                + constraints[i].included(uri, method));
232:                    if (constraints[i].included(uri, method)) {
233:                        if (results == null) {
234:                            results = new ArrayList();
235:                        }
236:                        results.add(constraints[i]);
237:                    }
238:                }
239:
240:                // No applicable security constraint was found
241:                if (debug)
242:                    log("  No applicable constraint located");
243:                if (results == null)
244:                    return null;
245:                SecurityConstraint[] array = new SecurityConstraint[results
246:                        .size()];
247:                System.arraycopy(results.toArray(), 0, array, 0, array.length);
248:                return array;
249:            }
250:
251:            /**
252:             * Initialize this <code>LoginModule</code> with the specified
253:             * configuration information.
254:             *
255:             * @param subject The <code>Subject</code> to be authenticated
256:             * @param callbackHandler A <code>CallbackHandler</code> for communicating
257:             *  with the end user as necessary
258:             * @param sharedState State information shared with other
259:             *  <code>LoginModule</code> instances
260:             * @param options Configuration information for this specific
261:             *  <code>LoginModule</code> instance
262:             */
263:            public void initialize(Subject subject,
264:                    CallbackHandler callbackHandler, Map sharedState,
265:                    Map options) {
266:                log.debug("Init");
267:
268:                // Save configuration values
269:                this .subject = subject;
270:                this .callbackHandler = callbackHandler;
271:                this .sharedState = sharedState;
272:                this .options = options;
273:
274:                // Perform instance-specific initialization
275:                this .debug = "true".equalsIgnoreCase((String) options
276:                        .get("debug"));
277:                if (options.get("pathname") != null)
278:                    this .pathname = (String) options.get("pathname");
279:
280:                // Load our defined Principals
281:                load();
282:
283:            }
284:
285:            /**
286:             * Phase 1 of authenticating a <code>Subject</code>.
287:             *
288:             * @return <code>true</code> if the authentication succeeded, or
289:             *  <code>false</code> if this <code>LoginModule</code> should be
290:             *  ignored
291:             *
292:             * @exception LoginException if the authentication fails
293:             */
294:            public boolean login() throws LoginException {
295:
296:                // Set up our CallbackHandler requests
297:                if (callbackHandler == null)
298:                    throw new LoginException("No CallbackHandler specified");
299:                Callback callbacks[] = new Callback[2];
300:                callbacks[0] = new NameCallback("Username: ");
301:                callbacks[1] = new PasswordCallback("Password: ", false);
302:
303:                // Interact with the user to retrieve the username and password
304:                String username = null;
305:                String password = null;
306:                try {
307:                    callbackHandler.handle(callbacks);
308:                    username = ((NameCallback) callbacks[0]).getName();
309:                    password = new String(((PasswordCallback) callbacks[1])
310:                            .getPassword());
311:                } catch (IOException e) {
312:                    throw new LoginException(e.toString());
313:                } catch (UnsupportedCallbackException e) {
314:                    throw new LoginException(e.toString());
315:                }
316:
317:                // Validate the username and password we have received
318:                principal = super .authenticate(username, password);
319:
320:                log.debug("login " + username + " " + principal);
321:
322:                // Report results based on success or failure
323:                if (principal != null) {
324:                    return (true);
325:                } else {
326:                    throw new FailedLoginException(
327:                            "Username or password is incorrect");
328:                }
329:
330:            }
331:
332:            /**
333:             * Log out this user.
334:             *
335:             * @return <code>true</code> in all cases because thie
336:             *  <code>LoginModule</code> should not be ignored
337:             *
338:             * @exception LoginException if logging out failed
339:             */
340:            public boolean logout() throws LoginException {
341:
342:                subject.getPrincipals().remove(principal);
343:                committed = false;
344:                principal = null;
345:                return (true);
346:
347:            }
348:
349:            // ---------------------------------------------------------- Realm Methods
350:            // ------------------------------------------------------ Protected Methods
351:
352:            /**
353:             * Load the contents of our configuration file.
354:             */
355:            protected void load() {
356:
357:                // Validate the existence of our configuration file
358:                File file = new File(pathname);
359:                if (!file.isAbsolute())
360:                    file = new File(System.getProperty("catalina.base"),
361:                            pathname);
362:                if (!file.exists() || !file.canRead()) {
363:                    log("Cannot load configuration file "
364:                            + file.getAbsolutePath());
365:                    return;
366:                }
367:
368:                // Load the contents of our configuration file
369:                Digester digester = new Digester();
370:                digester.setValidating(false);
371:                digester.addRuleSet(new MemoryRuleSet());
372:                try {
373:                    digester.push(this );
374:                    digester.parse(file);
375:                } catch (Exception e) {
376:                    log("Error processing configuration file "
377:                            + file.getAbsolutePath(), e);
378:                    return;
379:                }
380:
381:            }
382:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.