You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by cz...@apache.org on 2003/07/12 20:39:49 UTC
cvs commit: cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components PipelineAuthenticator.java DefaultAuthenticationManager.java Authenticator.java
cziegeler 2003/07/12 11:39:49
Modified: . status.xml
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration
HandlerConfiguration.java
src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components
DefaultAuthenticationManager.java
Authenticator.java
Added: src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components
PipelineAuthenticator.java
Log:
The authentication framework now uses a configurable component to try to authenticate a user.
This allows to drop in own authentication services or e.g. the servlet authentication mechanism.
Revision Changes Path
1.90 +5 -1 cocoon-2.1/status.xml
Index: status.xml
===================================================================
RCS file: /home/cvs/cocoon-2.1/status.xml,v
retrieving revision 1.89
retrieving revision 1.90
diff -u -r1.89 -r1.90
--- status.xml 12 Jul 2003 13:30:02 -0000 1.89
+++ status.xml 12 Jul 2003 18:39:48 -0000 1.90
@@ -184,6 +184,10 @@
<changes>
<release version="@version@" date="@date@">
+ <action dev="CZ" type="update">
+ The authentication framework now uses a configurable component to try to authenticate a user.
+ This allows to drop in own authentication services or e.g. the servlet authentication mechanism.
+ </action>
<action dev="JH" type="fix" fixes-bug="4934" due-to="Ryder Rishel" due-to-email=" ryderblue@yahoo.com">
Made JSPs working in Resin that don't end on *.jsp.
</action>
1.2 +21 -3 cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration/HandlerConfiguration.java
Index: HandlerConfiguration.java
===================================================================
RCS file: /home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/configuration/HandlerConfiguration.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- HandlerConfiguration.java 27 Apr 2003 12:52:53 -0000 1.1
+++ HandlerConfiguration.java 12 Jul 2003 18:39:49 -0000 1.2
@@ -59,6 +59,7 @@
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.Request;
+import org.apache.cocoon.webapps.authentication.components.PipelineAuthenticator;
import org.apache.excalibur.source.SourceParameters;
import org.apache.excalibur.source.SourceResolver;
import org.xml.sax.SAXException;
@@ -83,6 +84,9 @@
/** The authentication resource */
private String authenticationResource;
+
+ /** The class name of the authenticator to use */
+ private String authenticatorClass;
/** The authentication resource parameters */
private SourceParameters authenticationResourceParameters;
@@ -141,9 +145,16 @@
// get load resource (required)
child = conf.getChild("authentication", false);
- if (child == null)
+ if (child == null) {
throw new ConfigurationException("Handler '"+this.name+"' needs authentication configuration");
- this.authenticationResource = child.getAttribute("uri");
+ }
+ this.authenticatorClass = child.getAttribute("authenticator", PipelineAuthenticator.class.getName());
+ if ( PipelineAuthenticator.class.getName().equals(authenticatorClass)) {
+ this.authenticationResource = child.getAttribute("uri");
+ } else {
+ // the uri attribute is optional for other authenticators
+ this.authenticationResource = child.getAttribute("uri", null);
+ }
this.authenticationResourceParameters = SourceParameters.create(child);
// get load resource (optional)
@@ -268,5 +279,12 @@
*/
public String toString() {
return "authentication-Handler " + this.name;
+ }
+
+ /**
+ * Return the authenticator class
+ */
+ public String getAuthenticatorClassName() {
+ return this.authenticatorClass;
}
}
1.15 +53 -20 cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultAuthenticationManager.java
Index: DefaultAuthenticationManager.java
===================================================================
RCS file: /home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/DefaultAuthenticationManager.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- DefaultAuthenticationManager.java 1 Jul 2003 19:26:40 -0000 1.14
+++ DefaultAuthenticationManager.java 12 Jul 2003 18:39:49 -0000 1.15
@@ -51,6 +51,7 @@
package org.apache.cocoon.webapps.authentication.components;
import java.io.IOException;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -74,6 +75,7 @@
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Session;
+import org.apache.cocoon.util.ClassUtils;
import org.apache.cocoon.webapps.authentication.AuthenticationConstants;
import org.apache.cocoon.webapps.authentication.AuthenticationManager;
import org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
@@ -113,15 +115,15 @@
/** The Service Manager */
protected ServiceManager manager;
- /** The authenticator used to authenticate a user */
- protected Authenticator authenticator;
-
/** The Source Resolver */
protected SourceResolver resolver;
/** The context */
protected Context context;
+ /** Instantiated authenticators */
+ protected Map authenticators = new HashMap();
+
/** This is the key used to store the current request state in the request object */
private static final String REQUEST_STATE_KEY = RequestState.class.getName();
@@ -231,8 +233,12 @@
throw new ProcessingException("User is already authenticated using handler: " + handlerName);
}
- // This could be made pluggable, if required
- handler = this.authenticator.authenticate( config, parameters );
+ Authenticator authenticator = this.lookupAuthenticator( config );
+ try {
+ handler = authenticator.authenticate( config, parameters );
+ } finally {
+ this.releaseAuthenticator( authenticator, config );
+ }
if ( handler != null ) {
// create UserStatus
@@ -251,7 +257,42 @@
return handler;
}
- /* (non-Javadoc)
+ /**
+ * Release the used authenticator
+ */
+ protected void releaseAuthenticator(Authenticator authenticator, HandlerConfiguration config) {
+ // all authenticators are released on dispose
+ }
+
+ /**
+ * The authenticator used to authenticate a user
+ */
+ protected Authenticator lookupAuthenticator(HandlerConfiguration config)
+ throws ProcessingException {
+ final String name = config.getAuthenticatorClassName();
+ Authenticator authenticator = (Authenticator) this.authenticators.get(name);
+ if ( authenticator == null ) {
+ synchronized (this) {
+ authenticator = (Authenticator) this.authenticators.get(name);
+ if ( authenticator == null ) {
+ try {
+ authenticator = (Authenticator) ClassUtils.newInstance(name);
+ ContainerUtil.enableLogging( authenticator, this.getLogger() );
+ ContainerUtil.contextualize( authenticator, this.context);
+ ContainerUtil.service( authenticator, this.manager );
+ ContainerUtil.initialize( authenticator );
+ this.authenticators.put(name, authenticator);
+
+ } catch (Exception e ) {
+ throw new ProcessingException("Unable to initialize authenticator from class " + name, e);
+ }
+ }
+ }
+ }
+ return authenticator;
+ }
+
+ /* (non-Javadoc)
* @see org.apache.cocoon.webapps.authentication.components.Manager#checkAuthentication(org.apache.cocoon.environment.Redirector, java.lang.String, java.lang.String)
*/
public boolean checkAuthentication(Redirector redirector,
@@ -367,15 +408,6 @@
public void service(ServiceManager manager)
throws ServiceException {
this.manager = manager;
- this.authenticator = new Authenticator();
- try {
- ContainerUtil.enableLogging( this.authenticator, this.getLogger() );
- ContainerUtil.contextualize( this.authenticator, this.context);
- ContainerUtil.service( this.authenticator, this.manager );
- ContainerUtil.initialize( this.authenticator );
- } catch (Exception e ) {
- throw new ServiceException("Unable to initialize authenticator.", e);
- }
this.resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
}
@@ -383,10 +415,11 @@
* @see org.apache.avalon.framework.activity.Disposable#dispose()
*/
public void dispose() {
- if ( this.authenticator != null ) {
- ContainerUtil.dispose( this.authenticator );
- this.authenticator = null;
- }
+ Iterator iter = this.authenticators.values().iterator();
+ while ( iter.hasNext() ) {
+ final Authenticator authenticator = (Authenticator) iter.next();
+ ContainerUtil.dispose( authenticator );
+ }
if ( this.manager != null) {
this.manager.release( this.resolver );
this.manager = null;
1.8 +13 -294 cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Authenticator.java
Index: Authenticator.java
===================================================================
RCS file: /home/cvs/cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/Authenticator.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- Authenticator.java 1 Jul 2003 19:26:40 -0000 1.7
+++ Authenticator.java 12 Jul 2003 18:39:49 -0000 1.8
@@ -50,310 +50,29 @@
*/
package org.apache.cocoon.webapps.authentication.components;
-import java.io.IOException;
-import java.util.Iterator;
-
-import org.apache.avalon.framework.activity.Disposable;
-import org.apache.avalon.framework.component.Component;
-import org.apache.avalon.framework.context.Context;
-import org.apache.avalon.framework.context.ContextException;
-import org.apache.avalon.framework.context.Contextualizable;
-import org.apache.avalon.framework.logger.AbstractLogEnabled;
-import org.apache.avalon.framework.service.ServiceException;
-import org.apache.avalon.framework.service.ServiceManager;
-import org.apache.avalon.framework.service.Serviceable;
-import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.ProcessingException;
-import org.apache.cocoon.webapps.authentication.configuration.ApplicationConfiguration;
import org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
-import org.apache.cocoon.webapps.authentication.context.AuthenticationContext;
import org.apache.cocoon.webapps.authentication.user.UserHandler;
-import org.apache.cocoon.webapps.session.ContextManager;
-import org.apache.cocoon.webapps.session.MediaManager;
-import org.apache.cocoon.webapps.session.SessionConstants;
-import org.apache.cocoon.webapps.session.context.SessionContext;
-import org.apache.cocoon.xml.XMLUtils;
-import org.apache.cocoon.xml.dom.DOMUtil;
-import org.apache.excalibur.source.Source;
-import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.source.SourceParameters;
-import org.apache.excalibur.source.SourceResolver;
-import org.w3c.dom.Document;
-import org.w3c.dom.DocumentFragment;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-import org.xml.sax.SAXException;
/**
- * Verify if the a user could be authenticated.
- * This is a helper class that could be made pluggable if required.
+ * Verify if a user can be authenticated.
+ * An authenticator can implement all the usual component lifecycle interfaces
+ * and gets the information set.
+ * An authenticator must be implemented in a thread safe manner!
*
* @author <a href="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
* @version CVS $Id$
*/
-public class Authenticator
- extends AbstractLogEnabled
- implements Serviceable, ThreadSafe, Disposable, Contextualizable {
-
- /** The context */
- protected Context context;
-
- /** The service manager */
- protected ServiceManager manager;
-
- /** The source resolver */
- protected SourceResolver resolver;
-
- /**
- * Check the fragment if it is valid
- */
- private boolean isValidAuthenticationFragment(Document authenticationFragment)
- throws ProcessingException {
- // calling method is synced
- if (this.getLogger().isDebugEnabled() ) {
- this.getLogger().debug("BEGIN isValidAuthenticationFragment fragment=" + XMLUtils.serializeNodeToXML(authenticationFragment));
- }
- boolean isValid = false;
-
- // authenticationFragment must only have exactly one child with
- // the name authentication
- if (authenticationFragment.hasChildNodes() == true
- && authenticationFragment.getChildNodes().getLength() == 1) {
- Node child = authenticationFragment.getFirstChild();
-
- if (child.getNodeType() == Node.ELEMENT_NODE
- && child.getNodeName().equals("authentication") == true) {
-
- // now authentication must have one child ID
- if (child.hasChildNodes() == true) {
- NodeList children = child.getChildNodes();
- boolean found = false;
- int i = 0;
- int l = children.getLength();
-
- while (found == false && i < l) {
- child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE
- && child.getNodeName().equals("ID") == true) {
- found = true;
- } else {
- i++;
- }
- }
-
- // now the last check: ID must have a TEXT child
- if (found == true) {
- child.normalize(); // join text nodes
- if (child.hasChildNodes() == true &&
- child.getChildNodes().getLength() == 1 &&
- child.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
- String value = child.getChildNodes().item(0).getNodeValue().trim();
- if (value.length() > 0) isValid = true;
- }
- }
- }
-
- }
- }
- if (this.getLogger().isDebugEnabled()) {
- this.getLogger().debug("END isValidAuthenticationFragment valid="+isValid);
- }
- return isValid;
- }
+public interface Authenticator {
/**
* Try to authenticate the user.
- * @return A new {@link UserHandler} if authentication was successful
- * @throws ProcessingException
- */
- public UserHandler authenticate( HandlerConfiguration configuration,
- SourceParameters parameters)
- throws ProcessingException {
- if (this.getLogger().isDebugEnabled() ) {
- this.getLogger().debug("start authenticator using handler " + configuration.getName());
- }
-
- final String authenticationResourceName = configuration.getAuthenticationResource();
- final SourceParameters authenticationParameters = configuration.getAuthenticationResourceParameters();
- if (parameters != null) {
- parameters.add(authenticationParameters);
- } else {
- parameters = authenticationParameters;
- }
-
- Document doc = null;
- String exceptionMsg = null;
-
- // invoke the source
- try {
- Source source = null;
- try {
- source = org.apache.cocoon.components.source.SourceUtil.getSource(authenticationResourceName,
- null,
- parameters,
- this.resolver);
-
- doc = org.apache.cocoon.components.source.SourceUtil.toDOM(source);
- } catch (SAXException se) {
- throw new ProcessingException(se);
- } catch (SourceException se) {
- throw org.apache.cocoon.components.source.SourceUtil.handle(se);
- } catch (IOException e) {
- throw new ProcessingException(e);
- } finally {
- this.resolver.release(source);
- }
-
- } catch (ProcessingException local) {
- this.getLogger().error("authenticator: " + local.getMessage(), local);
- exceptionMsg = local.getMessage();
- }
-
- // test if authentication was successful
- boolean isValid = false;
- UserHandler handler = null;
- if (doc != null) {
- isValid = this.isValidAuthenticationFragment( doc );
-
- if ( isValid ) {
- if (this.getLogger().isInfoEnabled() ) {
- this.getLogger().info("Authenticator: User authenticated using handler '" + configuration.getName()+"'");
- }
-
- AuthenticationContext authContext = new AuthenticationContext(this.context);
- handler = new UserHandler(configuration, authContext);
-
- MediaManager mediaManager = null;
- String mediaType;
- try {
- mediaManager = (MediaManager)this.manager.lookup( MediaManager.ROLE );
- mediaType = mediaManager.getMediaType();
- } catch (ServiceException se) {
- throw new ProcessingException("Unable to lookup media manager.", se);
- } finally {
- this.manager.release( mediaManager );
- }
- synchronized(authContext) {
- // add special nodes to the authentication block:
- // useragent, type and media
- Element specialElement;
- Text specialValue;
- Element authNode;
-
- authNode = (Element)doc.getFirstChild();
-
- specialElement = doc.createElementNS(null, "type");
- specialValue = doc.createTextNode("cocoon.authentication");
- specialElement.appendChild(specialValue);
- authNode.appendChild(specialElement);
-
- specialElement = doc.createElementNS(null, "media");
- specialValue = doc.createTextNode(mediaType);
- specialElement.appendChild(specialValue);
- authNode.appendChild(specialElement);
-
- // store the authentication data in the context
- authContext.init(doc);
-
- // And now load applications
- boolean loaded = true;
- Iterator applications = configuration.getApplications().values().iterator();
-
- while ( applications.hasNext() ) {
- ApplicationConfiguration appHandler = (ApplicationConfiguration)applications.next();
- if ( !appHandler.getLoadOnDemand() ) {
- handler.getContext().loadApplicationXML( appHandler, this.resolver );
- } else {
- loaded = false;
- }
- }
-
- } // end sync
- }
- }
-
- if ( !isValid ) {
- if (this.getLogger().isInfoEnabled() ) {
- this.getLogger().info("Authenticator: Failed authentication using handler '" + configuration.getName()+"'");
- }
- // get the /authentication/data Node if available
- Node data = null;
-
- if (doc != null) {
- data = DOMUtil.getFirstNodeFromPath(doc, new String[] {"authentication","data"}, false);
- }
-
- // now create the following xml:
- // <failed/>
- // if data is available data is included, otherwise:
- // <data>No information</data>
- // If exception message contains info, it is included into failed
- DocumentFragment authenticationFragment = doc.createDocumentFragment();
-
- Element element = doc.createElementNS(null, "failed");
- authenticationFragment.appendChild(element);
-
- if (exceptionMsg != null) {
- Text text = doc.createTextNode(exceptionMsg);
- element.appendChild(text);
- }
-
- if (data == null) {
- element = doc.createElementNS(null, "data");
- authenticationFragment.appendChild(element);
- Text text = doc.createTextNode("No information");
- element.appendChild(text);
- } else {
- authenticationFragment.appendChild(doc.importNode(data, true));
- }
-
- // now set this information in the temporary context
- ContextManager sessionManager = null;
- try {
- sessionManager = (ContextManager) this.manager.lookup( ContextManager.ROLE );
- SessionContext temp = sessionManager.getContext( SessionConstants.TEMPORARY_CONTEXT );
- temp.appendXML("/", authenticationFragment);
- } catch ( ServiceException se ) {
- throw new ProcessingException("Unable to lookup session manager.", se);
- } finally {
- this.manager.release( (Component)sessionManager );
- }
- }
-
- if (this.getLogger().isDebugEnabled() ) {
- this.getLogger().debug("end authenticator");
- }
-
- return handler;
- }
-
-
- /* (non-Javadoc)
- * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
- */
- public void service(ServiceManager manager) throws ServiceException {
- this.manager = manager;
- this.resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
- }
-
- /* (non-Javadoc)
- * @see org.apache.avalon.framework.activity.Disposable#dispose()
- */
- public void dispose() {
- if ( this.manager != null ){
- this.manager.release( this.resolver );
- this.manager = null;
- this.resolver = null;
- }
- }
-
- /* (non-Javadoc)
- * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
+ * @return A new {@link UserHandler} if authentication was successful,
+ * otherwise null is returned.
+ * @throws ProcessingException Only if an error occurs
*/
- public void contextualize(Context context) throws ContextException {
- this.context = context;
- }
-
-}
+ public abstract UserHandler authenticate(HandlerConfiguration configuration,
+ SourceParameters parameters)
+ throws ProcessingException;
+}
\ No newline at end of file
1.1 cocoon-2.1/src/blocks/authentication-fw/java/org/apache/cocoon/webapps/authentication/components/PipelineAuthenticator.java
Index: PipelineAuthenticator.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
apache@apache.org.
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.webapps.authentication.components;
import java.io.IOException;
import java.util.Iterator;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.webapps.authentication.configuration.ApplicationConfiguration;
import org.apache.cocoon.webapps.authentication.configuration.HandlerConfiguration;
import org.apache.cocoon.webapps.authentication.context.AuthenticationContext;
import org.apache.cocoon.webapps.authentication.user.UserHandler;
import org.apache.cocoon.webapps.session.ContextManager;
import org.apache.cocoon.webapps.session.MediaManager;
import org.apache.cocoon.webapps.session.SessionConstants;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.xml.XMLUtils;
import org.apache.cocoon.xml.dom.DOMUtil;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.source.SourceParameters;
import org.apache.excalibur.source.SourceResolver;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* Verify if a user can be authenticated.
* This is a helper class that could be made pluggable if required.
*
* @author <a href="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
* @version CVS $Id: PipelineAuthenticator.java,v 1.1 2003/07/12 18:39:49 cziegeler Exp $
*/
public class PipelineAuthenticator
extends AbstractLogEnabled
implements Serviceable, ThreadSafe, Disposable, Contextualizable, Authenticator {
/** The context */
protected Context context;
/** The service manager */
protected ServiceManager manager;
/** The source resolver */
protected SourceResolver resolver;
/**
* Check the fragment if it is valid
*/
private boolean isValidAuthenticationFragment(Document authenticationFragment)
throws ProcessingException {
// calling method is synced
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN isValidAuthenticationFragment fragment=" + XMLUtils.serializeNodeToXML(authenticationFragment));
}
boolean isValid = false;
// authenticationFragment must only have exactly one child with
// the name authentication
if (authenticationFragment.hasChildNodes() == true
&& authenticationFragment.getChildNodes().getLength() == 1) {
Node child = authenticationFragment.getFirstChild();
if (child.getNodeType() == Node.ELEMENT_NODE
&& child.getNodeName().equals("authentication") == true) {
// now authentication must have one child ID
if (child.hasChildNodes() == true) {
NodeList children = child.getChildNodes();
boolean found = false;
int i = 0;
int l = children.getLength();
while (found == false && i < l) {
child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE
&& child.getNodeName().equals("ID") == true) {
found = true;
} else {
i++;
}
}
// now the last check: ID must have a TEXT child
if (found == true) {
child.normalize(); // join text nodes
if (child.hasChildNodes() == true &&
child.getChildNodes().getLength() == 1 &&
child.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
String value = child.getChildNodes().item(0).getNodeValue().trim();
if (value.length() > 0) isValid = true;
}
}
}
}
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("END isValidAuthenticationFragment valid="+isValid);
}
return isValid;
}
/**
* Try to authenticate the user.
* @return A new {@link UserHandler} if authentication was successful
* @throws ProcessingException
*/
public UserHandler authenticate( HandlerConfiguration configuration,
SourceParameters parameters)
throws ProcessingException {
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("start authenticator using handler " + configuration.getName());
}
final String authenticationResourceName = configuration.getAuthenticationResource();
final SourceParameters authenticationParameters = configuration.getAuthenticationResourceParameters();
if (parameters != null) {
parameters.add(authenticationParameters);
} else {
parameters = authenticationParameters;
}
Document doc = null;
String exceptionMsg = null;
// invoke the source
try {
Source source = null;
try {
source = org.apache.cocoon.components.source.SourceUtil.getSource(authenticationResourceName,
null,
parameters,
this.resolver);
doc = org.apache.cocoon.components.source.SourceUtil.toDOM(source);
} catch (SAXException se) {
throw new ProcessingException(se);
} catch (SourceException se) {
throw org.apache.cocoon.components.source.SourceUtil.handle(se);
} catch (IOException e) {
throw new ProcessingException(e);
} finally {
this.resolver.release(source);
}
} catch (ProcessingException local) {
this.getLogger().error("authenticator: " + local.getMessage(), local);
exceptionMsg = local.getMessage();
}
// test if authentication was successful
boolean isValid = false;
UserHandler handler = null;
if (doc != null) {
isValid = this.isValidAuthenticationFragment( doc );
if ( isValid ) {
if (this.getLogger().isInfoEnabled() ) {
this.getLogger().info("Authenticator: User authenticated using handler '" + configuration.getName()+"'");
}
AuthenticationContext authContext = new AuthenticationContext(this.context);
handler = new UserHandler(configuration, authContext);
MediaManager mediaManager = null;
String mediaType;
try {
mediaManager = (MediaManager)this.manager.lookup( MediaManager.ROLE );
mediaType = mediaManager.getMediaType();
} catch (ServiceException se) {
throw new ProcessingException("Unable to lookup media manager.", se);
} finally {
this.manager.release( mediaManager );
}
synchronized(authContext) {
// add special nodes to the authentication block:
// useragent, type and media
Element specialElement;
Text specialValue;
Element authNode;
authNode = (Element)doc.getFirstChild();
specialElement = doc.createElementNS(null, "type");
specialValue = doc.createTextNode("cocoon.authentication");
specialElement.appendChild(specialValue);
authNode.appendChild(specialElement);
specialElement = doc.createElementNS(null, "media");
specialValue = doc.createTextNode(mediaType);
specialElement.appendChild(specialValue);
authNode.appendChild(specialElement);
// store the authentication data in the context
authContext.init(doc);
// And now load applications
boolean loaded = true;
Iterator applications = configuration.getApplications().values().iterator();
while ( applications.hasNext() ) {
ApplicationConfiguration appHandler = (ApplicationConfiguration)applications.next();
if ( !appHandler.getLoadOnDemand() ) {
handler.getContext().loadApplicationXML( appHandler, this.resolver );
} else {
loaded = false;
}
}
} // end sync
}
}
if ( !isValid ) {
if (this.getLogger().isInfoEnabled() ) {
this.getLogger().info("Authenticator: Failed authentication using handler '" + configuration.getName()+"'");
}
// get the /authentication/data Node if available
Node data = null;
if (doc != null) {
data = DOMUtil.getFirstNodeFromPath(doc, new String[] {"authentication","data"}, false);
}
// now create the following xml:
// <failed/>
// if data is available data is included, otherwise:
// <data>No information</data>
// If exception message contains info, it is included into failed
DocumentFragment authenticationFragment = doc.createDocumentFragment();
Element element = doc.createElementNS(null, "failed");
authenticationFragment.appendChild(element);
if (exceptionMsg != null) {
Text text = doc.createTextNode(exceptionMsg);
element.appendChild(text);
}
if (data == null) {
element = doc.createElementNS(null, "data");
authenticationFragment.appendChild(element);
Text text = doc.createTextNode("No information");
element.appendChild(text);
} else {
authenticationFragment.appendChild(doc.importNode(data, true));
}
// now set this information in the temporary context
ContextManager sessionManager = null;
try {
sessionManager = (ContextManager) this.manager.lookup( ContextManager.ROLE );
SessionContext temp = sessionManager.getContext( SessionConstants.TEMPORARY_CONTEXT );
temp.appendXML("/", authenticationFragment);
} catch ( ServiceException se ) {
throw new ProcessingException("Unable to lookup session manager.", se);
} finally {
this.manager.release( (Component)sessionManager );
}
}
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("end authenticator");
}
return handler;
}
/* (non-Javadoc)
* @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
*/
public void service(ServiceManager manager) throws ServiceException {
this.manager = manager;
this.resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
}
/* (non-Javadoc)
* @see org.apache.avalon.framework.activity.Disposable#dispose()
*/
public void dispose() {
if ( this.manager != null ){
this.manager.release( this.resolver );
this.manager = null;
this.resolver = null;
}
}
/* (non-Javadoc)
* @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
*/
public void contextualize(Context context) throws ContextException {
this.context = context;
}
}