[jboss-cvs] JBossAS SVN: r79305 - in trunk: testsuite/src/main/org/jboss/test/security/test and 10 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Thu Oct 9 12:48:35 EDT 2008


Author: anil.saldhana at jboss.com
Date: 2008-10-09 12:48:35 -0400 (Thu, 09 Oct 2008)
New Revision: 79305

Added:
   trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIBasicUnitTestCase.java
   trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIFormUnitTestCase.java
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/roles.properties
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/users.properties
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/context.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/jboss-web.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/web.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/index.html
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/roles.properties
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/users.properties
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/context.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/jboss-web.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/web.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/error.jsp
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/index.html
   trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/login.jsp
   trunk/testsuite/src/resources/security/jaspi/jaspi-webbasic-jboss-beans.xml
   trunk/testsuite/src/resources/security/jaspi/jaspi-webform-jboss-beans.xml
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/SecurityActions.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPIAuthenticator.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPICallbackHandler.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPBasicServerAuthModule.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPFormServerAuthModule.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/SecurityActions.java
   trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/TomcatServerAuthModule.java
Modified:
   trunk/testsuite/imports/sections/security.xml
Log:
JBAS-6064: JSR-196 integration in web/tomcat layer - form and basic

Modified: trunk/testsuite/imports/sections/security.xml
===================================================================
--- trunk/testsuite/imports/sections/security.xml	2008-10-09 15:42:32 UTC (rev 79304)
+++ trunk/testsuite/imports/sections/security.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -380,5 +380,33 @@
 	</fileset>
      </jar>
 
+     <!--JASPI WEB Form -->
+     <war warfile="${build.lib}/jaspi-web-form.war"
+        webxml="${build.resources}/security/jaspi/jaspi-web-form.war/WEB-INF/web.xml">
+        <webinf dir="${build.resources}/security/jaspi/jaspi-web-form.war/WEB-INF">
+          <include name="jboss-web.xml"/>
+          <include name="context.xml"/>
+        </webinf>
+        <classes dir="${build.resources}/security/jaspi/jaspi-web-form.war/WEB-INF/classes"/>
+	<fileset dir="${build.resources}/security/jaspi/jaspi-web-form.war">
+	   <include name="*jsp"/>
+	   <include name="*html"/>
+	</fileset>
+     </war>
+
+     <!--JASPI WEB Basic -->
+     <war warfile="${build.lib}/jaspi-web-basic.war"
+        webxml="${build.resources}/security/jaspi/jaspi-web-basic.war/WEB-INF/web.xml">
+        <webinf dir="${build.resources}/security/jaspi/jaspi-web-basic.war/WEB-INF">
+          <include name="jboss-web.xml"/>
+          <include name="context.xml"/>
+        </webinf>
+        <classes dir="${build.resources}/security/jaspi/jaspi-web-basic.war/WEB-INF/classes"/>
+	<fileset dir="${build.resources}/security/jaspi/jaspi-web-basic.war">
+	   <include name="*jsp"/>
+	   <include name="*html"/>
+	</fileset>
+     </war>
+
    </target>
 </project>

Added: trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIBasicUnitTestCase.java
===================================================================
--- trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIBasicUnitTestCase.java	                        (rev 0)
+++ trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIBasicUnitTestCase.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,89 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.test;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.jboss.test.JBossTestCase;
+import org.jboss.test.JBossTestSetup;
+import org.jboss.test.util.web.HttpUtils;
+
+/**
+ * JSR-196: Web Basic Auth Unit Test Case
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 8, 2008
+ */
+public class WebJASPIBasicUnitTestCase extends JBossTestCase
+{
+   private static String login_config = "security/jaspi/jaspi-webbasic-jboss-beans.xml";
+   private String realm = "JASPI";
+   
+   private String username = "anil";
+   private String password = "cricket";
+
+   public WebJASPIBasicUnitTestCase(String name)
+   {
+      super(name); 
+   } 
+   
+   public void testBasicAuthSuccess() throws Exception
+   {   
+      String baseURL = HttpUtils.getBaseURL(username, password); 
+      URL url = new URL(baseURL+"jaspi-web-basic/");
+      HttpUtils.accessURL(url, realm, HttpURLConnection.HTTP_OK, HttpUtils.GET);
+   }
+   
+   public void testBasicAuthFailure() throws Exception
+   {
+      String baseURL = HttpUtils.getBaseURL(username, "BAD"); 
+      URL url = new URL(baseURL+"jaspi-web-basic/");
+      HttpUtils.accessURL(url, realm, HttpURLConnection.HTTP_UNAUTHORIZED, HttpUtils.GET); 
+   }  
+   
+   public static Test suite() throws Exception
+   {
+      TestSuite suite = new TestSuite();
+      suite.addTest(new TestSuite(WebJASPIBasicUnitTestCase.class));
+      // Create an initializer for the test suite
+      TestSetup wrapper = new JBossTestSetup(suite)
+      { 
+         protected void setUp() throws Exception
+         {
+            super.setUp();
+            deploy(getResourceURL(login_config)); 
+            deploy("jaspi-web-basic.war");
+         }
+         protected void tearDown() throws Exception
+         {   
+            undeploy("jaspi-web-basic.war");
+            undeploy(getResourceURL(login_config));
+            super.tearDown(); 
+         }
+      };
+      return wrapper; 
+   }  
+}
\ No newline at end of file

Added: trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIFormUnitTestCase.java
===================================================================
--- trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIFormUnitTestCase.java	                        (rev 0)
+++ trunk/testsuite/src/main/org/jboss/test/security/test/WebJASPIFormUnitTestCase.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,163 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.test;
+
+import java.net.HttpURLConnection;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpState;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.jboss.test.JBossTestCase;
+import org.jboss.test.JBossTestSetup;
+
+/**
+ * JSR-196: Web Form Auth Unit Test Case
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 8, 2008
+ */
+public class WebJASPIFormUnitTestCase extends JBossTestCase
+{
+   private static String login_config = "security/jaspi/jaspi-webform-jboss-beans.xml";
+   private String baseURLNoAuth ; 
+   private HttpClient httpConn = new HttpClient();
+   
+   private String username = "anil";
+   private String password = "cricket";
+
+   public WebJASPIFormUnitTestCase(String name)
+   {
+      super(name); 
+   }
+   
+   protected void setUp() throws Exception
+   {
+      super.setUp();
+      baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/"; 
+   }
+   
+   public void testFormAuthSuccess() throws Exception
+   {
+      GetMethod indexGet = new GetMethod(baseURLNoAuth+"jaspi-web-form/");
+      int responseCode = httpConn.executeMethod(indexGet);
+      String body = indexGet.getResponseBodyAsString();
+      assertTrue("Get OK("+responseCode+")", responseCode == HttpURLConnection.HTTP_OK);
+      assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
+
+      HttpState state = httpConn.getState();
+      Cookie[] cookies = state.getCookies();
+      String sessionID = null;
+      for(int c = 0; c < cookies.length; c ++)
+      {
+         Cookie k = cookies[c];
+         if( k.getName().equalsIgnoreCase("JSESSIONID") )
+            sessionID = k.getValue();
+      }
+      getLog().debug("Saw JSESSIONID="+sessionID);
+
+      // Submit the login form
+      PostMethod formPost = new PostMethod(baseURLNoAuth+"jaspi-web-form/j_security_check");
+      formPost.addRequestHeader("Referer", baseURLNoAuth+"jaspi-web-form/login.jsp");
+      formPost.addParameter("j_username", username);
+      formPost.addParameter("j_password", password);
+      responseCode = httpConn.executeMethod(formPost);
+      String response = formPost.getStatusText();
+      log.debug("responseCode="+responseCode+", response="+response);
+      assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
+
+      //  Follow the redirect to the SecureServlet
+      Header location = formPost.getResponseHeader("Location");
+      String indexURI = location.getValue();
+      GetMethod war1Index = new GetMethod(indexURI); 
+      responseCode = httpConn.executeMethod(war1Index);
+      response = war1Index.getStatusText();
+      log.debug("responseCode="+responseCode+", response="+response);
+      assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
+      body = war1Index.getResponseBodyAsString();
+      if( body.indexOf("j_security_check") > 0 )
+         fail("get of "+indexURI+" redirected to login page"); 
+      if( body.indexOf("Hi Anil") < 0 )
+         fail("index.html not seen");
+   }
+   
+   public void testFormAuthFailure() throws Exception
+   {
+      log.info("+++ testFormAuthFailure");
+      GetMethod indexGet = new GetMethod(baseURLNoAuth+"jaspi-web-form/");
+      int responseCode = httpConn.executeMethod(indexGet);
+      String body = indexGet.getResponseBodyAsString();
+      assertTrue("Get OK("+responseCode+")", responseCode == HttpURLConnection.HTTP_OK);
+      assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
+
+      HttpState state = httpConn.getState();
+      Cookie[] cookies = state.getCookies();
+      String sessionID = null;
+      for(int c = 0; c < cookies.length; c ++)
+      {
+         Cookie k = cookies[c];
+         if( k.getName().equalsIgnoreCase("JSESSIONID") )
+            sessionID = k.getValue();
+      }
+      getLog().debug("Saw JSESSIONID="+sessionID);
+
+      // Submit the login form
+      PostMethod formPost = new PostMethod(baseURLNoAuth+"jaspi-web-form/j_security_check");
+      formPost.addRequestHeader("Referer", baseURLNoAuth+"jaspi-web-form/login.jsp");
+      formPost.addParameter("j_username", "baduser");
+      formPost.addParameter("j_password", "badpass");
+      responseCode = httpConn.executeMethod(formPost);
+      String response = formPost.getStatusText();
+      log.debug("responseCode="+responseCode+", response="+response);
+      String responseBody = formPost.getResponseBodyAsString();
+      if(responseBody.indexOf("Errored") < 0)
+         fail("Error page not seen");  
+   } 
+   
+   public static Test suite() throws Exception
+   {
+      TestSuite suite = new TestSuite();
+      suite.addTest(new TestSuite(WebJASPIFormUnitTestCase.class));
+      // Create an initializer for the test suite
+      TestSetup wrapper = new JBossTestSetup(suite)
+      { 
+         protected void setUp() throws Exception
+         {
+            super.setUp();
+            deploy(getResourceURL(login_config)); 
+            deploy("jaspi-web-form.war");
+         }
+         protected void tearDown() throws Exception
+         {   
+            undeploy("jaspi-web-form.war");
+            undeploy(getResourceURL(login_config));
+            super.tearDown(); 
+         }
+      };
+      return wrapper; 
+   }  
+}

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/roles.properties
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/roles.properties	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/roles.properties	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+anil=architect

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/users.properties
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/users.properties	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/classes/users.properties	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+anil=cricket

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/context.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/context.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/context.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,5 @@
+<Context>
+<Valve
+className="org.jboss.web.tomcat.security.jaspi.TomcatJASPIAuthenticator"
+/>
+</Context>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/jboss-web.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/jboss-web.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/jboss-web.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,3 @@
+<jboss-web>
+<security-domain>java:/jaas/jaspi-test</security-domain>
+</jboss-web>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/web.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/web.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/WEB-INF/web.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
+  <security-constraint>
+    <web-resource-collection>
+      <web-resource-name>Home</web-resource-name>
+      <url-pattern>/*</url-pattern>
+    </web-resource-collection>
+    <auth-constraint>
+      <role-name>architect</role-name>
+    </auth-constraint>
+  </security-constraint>
+
+  <login-config>
+      <auth-method>BASIC</auth-method>
+      <realm-name>JASPI</realm-name>
+   </login-config>
+
+  <security-role>
+    <role-name>architect</role-name>
+  </security-role>
+</web-app>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/index.html
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/index.html	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-basic.war/index.html	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+Hi Anil

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/roles.properties
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/roles.properties	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/roles.properties	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+anil=architect

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/users.properties
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/users.properties	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/classes/users.properties	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+anil=cricket

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/context.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/context.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/context.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,5 @@
+<Context>
+<Valve
+className="org.jboss.web.tomcat.security.jaspi.TomcatJASPIAuthenticator"
+/>
+</Context>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/jboss-web.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/jboss-web.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/jboss-web.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,3 @@
+<jboss-web>
+<security-domain>java:/jaas/jaspi-test</security-domain>
+</jboss-web>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/web.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/web.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/WEB-INF/web.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
+  <security-constraint>
+    <web-resource-collection>
+      <web-resource-name>Home</web-resource-name>
+      <url-pattern>/*</url-pattern>
+    </web-resource-collection>
+    <auth-constraint>
+      <role-name>architect</role-name>
+    </auth-constraint>
+  </security-constraint>
+
+  <login-config>
+    <auth-method>form</auth-method>
+    <form-login-config>
+      <form-login-page>/login.jsp</form-login-page>
+      <form-error-page>/error.jsp</form-error-page>
+    </form-login-config>
+  </login-config>
+
+  <security-role>
+    <role-name>architect</role-name>
+  </security-role>
+</web-app>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/error.jsp
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/error.jsp	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/error.jsp	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+Errored out

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/index.html
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/index.html	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/index.html	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1 @@
+Hi Anil

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/login.jsp
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/login.jsp	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-web-form.war/login.jsp	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,11 @@
+<form action='j_security_check' method='post'>
+<table>
+ <tr><td>Name:</td>
+   <td><input type='text' name='j_username'></td></tr>
+ <tr><td>Password:</td> 
+   <td><input type='password' name='j_password' size='8'></td>
+ </tr>
+</table>
+<br>
+  <input type='submit' value='login'> 
+</form>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-webbasic-jboss-beans.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-webbasic-jboss-beans.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-webbasic-jboss-beans.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+   <application-policy xmlns="urn:jboss:security-beans:1.0" name="jaspi-test">
+       <authentication-jaspi>
+         <login-module-stack name="lm-stack">
+           <login-module
+              code="org.jboss.security.auth.spi.UsersRolesLoginModule"
+              flag="required">
+           </login-module>
+         </login-module-stack>
+         <auth-module code="org.jboss.web.tomcat.security.jaspi.modules.HTTPBasicServerAuthModule" login-module-stack-ref="lm-stack"/>
+       </authentication-jaspi>
+   </application-policy>
+
+</deployment>

Added: trunk/testsuite/src/resources/security/jaspi/jaspi-webform-jboss-beans.xml
===================================================================
--- trunk/testsuite/src/resources/security/jaspi/jaspi-webform-jboss-beans.xml	                        (rev 0)
+++ trunk/testsuite/src/resources/security/jaspi/jaspi-webform-jboss-beans.xml	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+   <application-policy xmlns="urn:jboss:security-beans:1.0" name="jaspi-test">
+       <authentication-jaspi>
+         <login-module-stack name="lm-stack">
+           <login-module
+              code="org.jboss.security.auth.spi.UsersRolesLoginModule"
+              flag="required">
+           </login-module>
+         </login-module-stack>
+         <auth-module code="org.jboss.web.tomcat.security.jaspi.modules.HTTPFormServerAuthModule" login-module-stack-ref="lm-stack"/>
+       </authentication-jaspi>
+   </application-policy>
+
+</deployment>

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/SecurityActions.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/SecurityActions.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/SecurityActions.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,70 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * Privileged Blocks
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 8, 2008
+ */
+class SecurityActions
+{
+   static Class<?> loadClass(final String fqn) throws PrivilegedActionException
+   {
+     return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>()
+     {
+        public Class<?> run() throws Exception
+        {
+           ClassLoader tcl = getContextClassLoader();
+           return tcl.loadClass(fqn); 
+        }
+     });  
+   } 
+   
+   static ClassLoader getContextClassLoader()
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+      {
+         public ClassLoader run()
+         {
+            return Thread.currentThread().getContextClassLoader();
+         }
+      });
+   }
+   
+   static void setContextClassLoader(final ClassLoader tccl)
+   {
+      AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+      {
+         public ClassLoader run()
+         {
+            Thread.currentThread().setContextClassLoader(tccl);
+            return null;
+         }
+      });
+   }
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPIAuthenticator.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPIAuthenticator.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPIAuthenticator.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,247 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi;
+
+import java.io.IOException;
+import java.security.Principal;
+
+import javax.security.auth.Subject;
+import javax.security.auth.message.callback.CallerPrincipalCallback;
+import javax.security.auth.message.callback.PasswordValidationCallback;
+import javax.servlet.http.Cookie;
+
+import org.apache.catalina.Session;
+import org.apache.catalina.authenticator.AuthenticatorBase;
+import org.apache.catalina.authenticator.Constants;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.apache.catalina.deploy.LoginConfig;
+import org.jboss.logging.Logger;
+import org.jboss.security.ServerAuthenticationManager;
+import org.jboss.security.auth.message.GenericMessageInfo;
+import org.jboss.security.plugins.auth.JASPIServerAuthenticationManager;
+
+/**
+ * Tomcat authenticator that does JSR-196 (JASPI) authentication
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 7, 2008
+ */
+public class TomcatJASPIAuthenticator extends AuthenticatorBase
+{
+   private static Logger log = Logger.getLogger(TomcatJASPIAuthenticator.class);
+   
+   private String messageLayer = "HttpServlet";
+   
+   protected String serverAuthenticationManagerClass = JASPIServerAuthenticationManager.class.getName();
+ 
+   @Override
+   protected boolean authenticate(Request request, Response response, LoginConfig config) throws IOException
+   { 
+      boolean result = false;
+      
+      String authMethod = config.getAuthMethod(); 
+
+      // Have we already authenticated someone?
+      Principal principal = request.getUserPrincipal();
+      String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
+      if (principal != null) {
+         log.trace("Already authenticated '" + principal.getName() + "'");
+         // Associate the session with any existing SSO session
+         if (ssoId != null)
+            associate(ssoId, request.getSessionInternal(true));
+         return (true);
+      }
+
+      if("BASIC".equalsIgnoreCase(authMethod) ||
+            "FORM".equalsIgnoreCase(authMethod) )
+      {
+         // Is there an SSO session against which we can try to reauthenticate?
+         if (ssoId != null) {
+            log.trace("SSO Id " + ssoId + " set; attempting " +
+               "reauthentication");
+            /* Try to reauthenticate using data cached by SSO.  If this fails,
+                either the original SSO logon was of DIGEST or SSL (which
+                we can't reauthenticate ourselves because there is no
+                cached username and password), or the realm denied
+                the user's reauthentication for some reason.
+                In either case we have to prompt the user for a logon */
+            if (reauthenticateFromSSO(ssoId, request))
+               return true;
+         }
+      }      
+
+      GenericMessageInfo messageInfo = new GenericMessageInfo();
+      messageInfo.setRequestMessage(request);
+      messageInfo.setResponseMessage(response);
+      
+      //Put bits of information needed by tomcat server auth modules
+      messageInfo.getMap().put("CACHE", cache); 
+      
+      TomcatJASPICallbackHandler cbh = new TomcatJASPICallbackHandler();
+      
+      ServerAuthenticationManager sam = getServerAuthenticationManager();
+      if(sam != null)
+      {
+         result = sam.isValid(messageInfo, new Subject(), messageLayer, cbh);
+      } 
+      
+      //The Authentication process has been a success. We need to register
+      //the principal, username, password with the container
+      if(result)
+      {
+         PasswordValidationCallback pvc = cbh.getPasswordValidationCallback();
+         CallerPrincipalCallback cpcb = cbh.getCallerPrincipalCallback();
+         this.register(request, response, cpcb.getPrincipal(), authMethod, 
+               pvc.getUsername(), new String(pvc.getPassword()));
+      }
+      
+      return result; 
+   }
+
+   /**
+    * Get the FQN of the class that implements
+    * the org.jboss.security.ServerAuthenticationManager intepasswordrface
+    * @return
+    */
+   public String getServerAuthenticationManagerClass()
+   {
+      return serverAuthenticationManagerClass;
+   }
+
+   /**
+    * Set the FQN of the class that implements
+    * the org.jboss.security.ServerAuthenticationManager interface
+    * @param serverAuthenticationManagerClass
+    */
+   public void setServerAuthenticationManagerClass(String serverAuthenticationManagerClass)
+   {
+      this.serverAuthenticationManagerClass = serverAuthenticationManagerClass;
+   } 
+   
+   protected ServerAuthenticationManager getServerAuthenticationManager()
+   {
+      ServerAuthenticationManager sam = null;
+      Class<?> clazz;
+      try
+      {
+         clazz = SecurityActions.loadClass(serverAuthenticationManagerClass);
+         sam = (ServerAuthenticationManager) clazz.newInstance();
+      }
+      catch (Exception e)
+      {
+         log.error("Exception in obtaining ServerAuthenticationManager:", e);
+      } 
+      
+      return sam;
+   }
+   
+   /**
+    * Register an authenticated Principal and authentication type in our
+    * request, in the current session (if there is one), and with our
+    * SingleSignOn valve, if there is one.  Set the appropriate cookie
+    * to be returned.
+    *
+    * @param request The servlet request we are processing
+    * @param response The servlet response we are generating
+    * @param principal The authenticated Principal to be registered
+    * @param authType The authentication type to be registered
+    * @param username Username used to authenticate (if any)
+    * @param password Password used to authenticate (if any)
+    */
+   protected void register(Request request, Response response,
+                           Principal principal, String authType,
+                           String username, String password) {
+
+       if (log.isTraceEnabled()) {
+           // Bugzilla 39255: http://issues.apache.org/bugzilla/show_bug.cgi?id=39255
+           String name = (principal == null) ? "none" : principal.getName();
+           log.trace("Authenticated '" + name + "' with type '"
+               + authType + "'");
+       }
+
+       // Cache the authentication information in our request
+       request.setAuthType(authType);
+       request.setUserPrincipal(principal);
+
+       Session session = request.getSessionInternal(false);
+       // Cache the authentication information in our session, if any
+       if (cache) {
+           if (session != null) {
+               session.setAuthType(authType);
+               session.setPrincipal(principal);
+               if (username != null)
+                   session.setNote(Constants.SESS_USERNAME_NOTE, username);
+               else
+                   session.removeNote(Constants.SESS_USERNAME_NOTE);
+               if (password != null)
+                   session.setNote(Constants.SESS_PASSWORD_NOTE, password);
+               else
+                   session.removeNote(Constants.SESS_PASSWORD_NOTE);
+           }
+       }
+
+       // Construct a cookie to be returned to the client
+       if (sso == null)
+           return;
+
+       // Only create a new SSO entry if the SSO did not already set a note
+       // for an existing entry (as it would do with subsequent requests
+       // for DIGEST and SSL authenticated contexts)
+       String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
+       if (ssoId == null) {
+           // Construct a cookie to be returned to the client
+           ssoId = generateSessionId();
+           Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, ssoId);
+           cookie.setMaxAge(-1);
+           cookie.setPath("/");
+           
+           // Bugzilla 41217
+           cookie.setSecure(request.isSecure());
+           
+           // Bugzilla 34724
+           String ssoDomain = sso.getCookieDomain();
+           if(ssoDomain != null) {
+               cookie.setDomain(ssoDomain);
+           }
+
+           response.addCookie(cookie);
+
+           // Register this principal with our SSO valve
+           sso.register(ssoId, principal, authType, username, password);
+           request.setNote(Constants.REQ_SSOID_NOTE, ssoId);
+
+       } else {
+           // Update the SSO session with the latest authentication data
+           sso.update(ssoId, principal, authType, username, password);
+       }
+
+       // Fix for Bug 10040
+       // Always associate a session with a new SSO reqistration.
+       // SSO entries are only removed from the SSO registry map when
+       // associated sessions are destroyed; if a new SSO entry is created
+       // above for this request and the user never revisits the context, the
+       // SSO entry will never be cleared if we don't associate the session
+       if (session == null)
+           session = request.getSessionInternal(true);
+       sso.associate(ssoId, session); 
+   }
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPICallbackHandler.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPICallbackHandler.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/TomcatJASPICallbackHandler.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,103 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi;
+
+import java.io.IOException;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.message.callback.CallerPrincipalCallback;
+import javax.security.auth.message.callback.GroupPrincipalCallback;
+import javax.security.auth.message.callback.PasswordValidationCallback;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Callback handler for JASPI Web Profile
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 8, 2008
+ */
+public class TomcatJASPICallbackHandler implements CallbackHandler
+{
+   private static Logger log = Logger.getLogger(TomcatJASPICallbackHandler.class);
+   
+   private CallerPrincipalCallback callerPrincipalCallback;
+   private PasswordValidationCallback passwordValidationCallback;
+   private GroupPrincipalCallback groupPrincipalCallback;
+
+   public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
+   {
+      if(callbacks.length > 0)
+      {
+         for(Callback callback: callbacks)
+         {
+           if(callback instanceof CallerPrincipalCallback)
+           {
+              callback = this.callerPrincipalCallback;
+           }
+           else
+           if(callback instanceof PasswordValidationCallback)
+           {
+              callback = this.passwordValidationCallback;
+           }
+           else
+           if(callback instanceof GroupPrincipalCallback)
+           {
+              callback = this.groupPrincipalCallback;
+           }
+           else
+              log.trace("Callback " + callback.getClass().getCanonicalName() + " not supported");
+         } 
+      }
+   }
+    
+   public CallerPrincipalCallback getCallerPrincipalCallback()
+   {
+      return callerPrincipalCallback;
+   }
+
+   public PasswordValidationCallback getPasswordValidationCallback()
+   {
+      return passwordValidationCallback;
+   }
+
+   public GroupPrincipalCallback getGroupPrincipalCallback()
+   {
+      return groupPrincipalCallback;
+   }
+
+   public void setCallerPrincipalCallback(CallerPrincipalCallback callerPrincipalCallback)
+   {
+     this.callerPrincipalCallback =  callerPrincipalCallback;
+   }
+   
+   public void setGroupPrincipalCallback(GroupPrincipalCallback groupPrincipalCallback)
+   {
+      this.groupPrincipalCallback = groupPrincipalCallback;
+   }
+   
+   public void setPasswordValidationCallback(PasswordValidationCallback passwordValidationCallback)
+   {
+      this.passwordValidationCallback = passwordValidationCallback;
+   }
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPBasicServerAuthModule.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPBasicServerAuthModule.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPBasicServerAuthModule.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,188 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi.modules;
+
+import java.io.IOException;
+import java.security.Principal;
+
+import javax.security.auth.Subject;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.authenticator.Constants;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.apache.catalina.deploy.LoginConfig;
+import org.apache.catalina.util.Base64;
+import org.apache.catalina.util.StringManager;
+import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.buf.CharChunk;
+import org.apache.tomcat.util.buf.MessageBytes;
+import org.jboss.logging.Logger;
+
+/**
+ * Server auth module for Basic authentication
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 7, 2008
+ */
+public class HTTPBasicServerAuthModule extends TomcatServerAuthModule
+{
+   private static Logger log = Logger.getLogger(HTTPBasicServerAuthModule.class);
+
+   protected Context context; 
+   
+   protected boolean cache = false;
+   
+   protected static final StringManager sm =
+      StringManager.getManager(Constants.Package);
+   
+   /**
+    * Authenticate bytes.
+    */
+   public static final byte[] AUTHENTICATE_BYTES = {
+       (byte) 'W',
+       (byte) 'W',
+       (byte) 'W',
+       (byte) '-',
+       (byte) 'A',
+       (byte) 'u',
+       (byte) 't',
+       (byte) 'h',
+       (byte) 'e',
+       (byte) 'n',
+       (byte) 't',
+       (byte) 'i',
+       (byte) 'c',
+       (byte) 'a',
+       (byte) 't',
+       (byte) 'e'
+   };
+
+   
+   /**
+    * The number of random bytes to include when generating a
+    * session identifier.
+    */
+   protected static final int SESSION_ID_BYTES = 16;
+
+   protected String delgatingLoginContextName = null;
+   
+   public HTTPBasicServerAuthModule()
+   { 
+   }
+ 
+   public HTTPBasicServerAuthModule(String delgatingLoginContextName)
+   {
+      super();
+      this.delgatingLoginContextName = delgatingLoginContextName;
+   }
+
+   public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject)
+   throws AuthException
+   {
+      throw new RuntimeException("Not Applicable");
+   }
+
+   public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, 
+         Subject serviceSubject) throws AuthException
+   { 
+      Request request = (Request) messageInfo.getRequestMessage();
+      Response response = (Response) messageInfo.getResponseMessage();
+     
+      Principal principal;
+      context = request.getContext();
+      LoginConfig config = context.getLoginConfig(); 
+      
+      // Validate any credentials already included with this request
+      String username = null;
+      String password = null;
+
+      MessageBytes authorization = 
+          request.getCoyoteRequest().getMimeHeaders()
+          .getValue("authorization");
+      
+      if (authorization != null) {
+          authorization.toBytes();
+          ByteChunk authorizationBC = authorization.getByteChunk();
+          if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
+              authorizationBC.setOffset(authorizationBC.getOffset() + 6);
+              // FIXME: Add trimming
+              // authorizationBC.trim();
+              
+              CharChunk authorizationCC = authorization.getCharChunk();
+              Base64.decode(authorizationBC, authorizationCC);
+              
+              // Get username and password
+              int colon = authorizationCC.indexOf(':');
+              if (colon < 0) {
+                  username = authorizationCC.toString();
+              } else {
+                  char[] buf = authorizationCC.getBuffer();
+                  username = new String(buf, 0, colon);
+                  password = new String(buf, colon + 1, 
+                          authorizationCC.getEnd() - colon - 1);
+              }
+              
+              authorizationBC.setOffset(authorizationBC.getOffset() - 6);
+          }
+
+          principal = context.getRealm().authenticate(username, password);
+          if (principal != null) {
+             registerWithCallbackHandler(principal, username, password);
+             
+              /*register(request, response, principal, Constants.BASIC_METHOD,
+                       username, password);*/
+             return AuthStatus.SUCCESS; 
+          }
+      } 
+
+      // Send an "unauthorized" response and an appropriate challenge
+      MessageBytes authenticate = 
+          response.getCoyoteResponse().getMimeHeaders()
+          .addValue(AUTHENTICATE_BYTES, 0, AUTHENTICATE_BYTES.length);
+      CharChunk authenticateCC = authenticate.getCharChunk();
+      try
+      {
+         authenticateCC.append("Basic realm=\"");
+         if (config.getRealmName() == null) {
+            authenticateCC.append(request.getServerName());
+            authenticateCC.append(':');
+            authenticateCC.append(Integer.toString(request.getServerPort()));
+         } else {
+            authenticateCC.append(config.getRealmName());
+         }
+         authenticateCC.append('\"');        
+         authenticate.toChars();
+
+         response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+      }
+      catch (IOException e)
+      {
+         log.error("IOException ", e); 
+      }
+      //response.flushBuffer();
+      return AuthStatus.FAILURE;  
+   } 
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPFormServerAuthModule.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPFormServerAuthModule.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/HTTPFormServerAuthModule.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,522 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi.modules;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.Principal;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Locale;
+
+import javax.security.auth.Subject;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.Realm;
+import org.apache.catalina.Session;
+import org.apache.catalina.authenticator.Constants;
+import org.apache.catalina.authenticator.SavedRequest;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.apache.catalina.deploy.LoginConfig;
+import org.apache.catalina.util.StringManager;
+import org.apache.coyote.ActionCode;
+import org.apache.tomcat.util.buf.ByteChunk;
+import org.apache.tomcat.util.buf.CharChunk;
+import org.apache.tomcat.util.buf.MessageBytes;
+import org.apache.tomcat.util.http.MimeHeaders;
+import org.jboss.logging.Logger;
+
+/**
+ * Server auth module for FORM authentication
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 7, 2008
+ */
+public class HTTPFormServerAuthModule extends TomcatServerAuthModule
+{
+   private static Logger log = Logger.getLogger(HTTPFormServerAuthModule.class);
+
+   protected Context context; 
+   
+   protected boolean cache = false;
+   
+   protected static final StringManager sm =
+      StringManager.getManager(Constants.Package);
+   
+   /**
+    * The number of random bytes to include when generating a
+    * session identifier.
+    */
+   protected static final int SESSION_ID_BYTES = 16;
+
+   protected String delgatingLoginContextName = null;
+   
+   public HTTPFormServerAuthModule()
+   { 
+   }
+ 
+   public HTTPFormServerAuthModule(String delgatingLoginContextName)
+   {
+      super();
+      this.delgatingLoginContextName = delgatingLoginContextName;
+   }
+
+   public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject)
+   throws AuthException
+   {
+      throw new RuntimeException("Not Applicable");
+   }
+
+   public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, 
+         Subject serviceSubject) throws AuthException
+   { 
+      Request request = (Request) messageInfo.getRequestMessage();
+      Response response = (Response) messageInfo.getResponseMessage();
+     
+      Principal principal;
+      context = request.getContext();
+      LoginConfig config = context.getLoginConfig();
+       
+      // References to objects we will need later
+      Session session = null;
+
+      //Lets find out if the cache is enabled or not 
+      cache = (Boolean) messageInfo.getMap().get("CACHE"); 
+      
+      // Have we authenticated this user before but have caching disabled?
+      if (!cache) {
+          session = request.getSessionInternal(true);
+          log.debug("Checking for reauthenticate in session " + session);
+          String username =
+              (String) session.getNote(Constants.SESS_USERNAME_NOTE);
+          String password =
+              (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
+          if ((username != null) && (password != null)) {
+              log.debug("Reauthenticating username '" + username + "'");
+              principal =
+                  context.getRealm().authenticate(username, password);
+              if (principal != null) {
+                  session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
+                  if (!matchRequest(request)) {
+                     registerWithCallbackHandler(principal, username, password);
+                     
+                      /*register(request, response, principal,
+                               Constants.FORM_METHOD,
+                               username, password);*/
+                      return AuthStatus.SUCCESS;
+                  }
+              }
+              log.trace("Reauthentication failed, proceed normally");
+          }
+      }
+
+      // Is this the re-submit of the original request URI after successful
+      // authentication?  If so, forward the *original* request instead.
+      if (matchRequest(request)) {
+          session = request.getSessionInternal(true);
+          log.trace("Restore request from session '"
+                        + session.getIdInternal() 
+                        + "'");
+          principal = (Principal)
+              session.getNote(Constants.FORM_PRINCIPAL_NOTE);
+          
+          registerWithCallbackHandler(principal, 
+                (String) session.getNote(Constants.SESS_USERNAME_NOTE), 
+                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
+          
+          /*register(request, response, principal, Constants.FORM_METHOD,
+                   (String) session.getNote(Constants.SESS_USERNAME_NOTE),
+                   (String) session.getNote(Constants.SESS_PASSWORD_NOTE));*/
+          // If we're caching principals we no longer need the username
+          // and password in the session, so remove them
+          if (cache) {
+              session.removeNote(Constants.SESS_USERNAME_NOTE);
+              session.removeNote(Constants.SESS_PASSWORD_NOTE);
+          }
+          if (restoreRequest(request, session)) {
+              log.trace("Proceed to restored request");
+              return (AuthStatus.SUCCESS);
+          } else {
+              log.trace("Restore of original request failed");
+            
+            try
+            {
+               response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+            }
+            catch (IOException e)
+            {
+               log.error(e.getLocalizedMessage(),e);
+            }
+              return AuthStatus.FAILURE;
+          }
+      }
+
+      // Acquire references to objects we will need to evaluate
+      MessageBytes uriMB = MessageBytes.newInstance();
+      CharChunk uriCC = uriMB.getCharChunk();
+      uriCC.setLimit(-1);
+      String contextPath = request.getContextPath();
+      String requestURI = request.getDecodedRequestURI();
+      response.setContext(request.getContext());
+
+      // Is this the action request from the login page?
+      boolean loginAction =
+          requestURI.startsWith(contextPath) &&
+          requestURI.endsWith(Constants.FORM_ACTION);
+
+      // No -- Save this request and redirect to the form login page
+      if (!loginAction) {
+          session = request.getSessionInternal(true);
+          log.trace("Save request in session '" + session.getIdInternal() + "'");
+          try {
+              saveRequest(request, session);
+          } catch (IOException ioe) {
+              log.trace("Request body too big to save during authentication");
+              try
+            {
+               response.sendError(HttpServletResponse.SC_FORBIDDEN,
+                         sm.getString("authenticator.requestBodyTooBig"));
+            }
+            catch (IOException e)
+            {
+               log.error("Exception in Form authentication:",e);
+               throw new AuthException(e.getLocalizedMessage());
+            }
+              return (AuthStatus.FAILURE);
+          }
+          forwardToLoginPage(request, response, config);
+          return (AuthStatus.SEND_CONTINUE);
+      }
+
+      // Yes -- Validate the specified credentials and redirect
+      // to the error page if they are not correct
+      Realm realm = context.getRealm();
+      String characterEncoding = request.getCharacterEncoding();
+      if (characterEncoding != null) {
+          try
+         {
+            request.setCharacterEncoding(characterEncoding);
+         }
+         catch (UnsupportedEncodingException e)
+         {
+            log.error(e.getLocalizedMessage(), e);
+         }
+      }
+      String username = request.getParameter(Constants.FORM_USERNAME);
+      String password = request.getParameter(Constants.FORM_PASSWORD);
+      log.trace("Authenticating username '" + username + "'");
+      principal = realm.authenticate(username, password);
+      if (principal == null) {
+          forwardToErrorPage(request, response, config);
+          return (AuthStatus.FAILURE);
+      }
+
+      log.trace("Authentication of '" + username + "' was successful");
+
+      if (session == null)
+          session = request.getSessionInternal(false);
+      if (session == null) {
+          log.trace
+                  ("User took so long to log on the session expired");
+          try
+         {
+            response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
+                                sm.getString("authenticator.sessionExpired"));
+         }
+         catch (IOException e)
+         {
+            log.error(e.getLocalizedMessage(),e);
+         }
+          return (AuthStatus.FAILURE);
+      }
+
+      // Save the authenticated Principal in our session
+      session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
+
+      // Save the username and password as well
+      session.setNote(Constants.SESS_USERNAME_NOTE, username);
+      session.setNote(Constants.SESS_PASSWORD_NOTE, password);
+
+      // Redirect the user to the original request URI (which will cause
+      // the original request to be restored)
+      requestURI = savedRequestURL(session);
+      log.trace("Redirecting to original '" + requestURI + "'");
+      try
+      {
+         if (requestURI == null)
+            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
+                               sm.getString("authenticator.formlogin"));
+        else
+            response.sendRedirect(response.encodeRedirectURL(requestURI));  
+      }
+      catch(IOException ioe)
+      {
+         log.error(ioe.getLocalizedMessage(),ioe);
+      }
+      return (AuthStatus.FAILURE); 
+   }
+   
+   /**
+    * Does this request match the saved one (so that it must be the redirect
+    * we signalled after successful authentication?
+    *
+    * @param request The request to be verified
+    */
+   protected boolean matchRequest(Request request) 
+   { 
+     // Has a session been created?
+     Session session = request.getSessionInternal(false);
+     if (session == null)
+         return (false);
+
+     // Is there a saved request?
+     SavedRequest sreq = (SavedRequest)
+         session.getNote(Constants.FORM_REQUEST_NOTE);
+     if (sreq == null)
+         return (false);
+
+     // Is there a saved principal?
+     if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null)
+         return (false);
+
+     // Does the request URI match?
+     String requestURI = request.getRequestURI();
+     if (requestURI == null)
+         return (false);
+     return (requestURI.equals(sreq.getRequestURI()));
+
+   }
+
+
+   /**
+    * Restore the original request from information stored in our session.
+    * If the original request is no longer present (because the session
+    * timed out), return <code>false</code>; otherwise, return
+    * <code>true</code>.
+    *
+    * @param request The request to be restored
+    * @param session The session containing the saved information
+    */
+   @SuppressWarnings("unchecked")
+   protected boolean restoreRequest(Request request, Session session) 
+   { 
+       // Retrieve and remove the SavedRequest object from our session
+       SavedRequest saved = (SavedRequest)
+           session.getNote(Constants.FORM_REQUEST_NOTE);
+       session.removeNote(Constants.FORM_REQUEST_NOTE);
+       session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
+       if (saved == null)
+           return (false);
+
+       // Modify our current request to reflect the original one
+       request.clearCookies();
+       Iterator cookies = saved.getCookies();
+       while (cookies.hasNext()) {
+           request.addCookie((Cookie) cookies.next());
+       }
+
+       MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
+       rmh.recycle();
+       boolean cachable = "GET".equalsIgnoreCase(saved.getMethod()) ||
+                          "HEAD".equalsIgnoreCase(saved.getMethod());
+       Iterator names = saved.getHeaderNames();
+       while (names.hasNext()) {
+           String name = (String) names.next();
+           // The browser isn't expecting this conditional response now.
+           // Assuming that it can quietly recover from an unexpected 412.
+           // BZ 43687
+           if(!("If-Modified-Since".equalsIgnoreCase(name) ||
+                (cachable && "If-None-Match".equalsIgnoreCase(name)))) {
+               Iterator values = saved.getHeaderValues(name);
+               while (values.hasNext()) {
+                   rmh.addValue(name).setString( (String)values.next() );
+               }
+           }
+       }
+       
+       request.clearLocales();
+       Iterator locales = saved.getLocales();
+       while (locales.hasNext()) {
+           request.addLocale((Locale) locales.next());
+       }
+       
+       request.getCoyoteRequest().getParameters().recycle();
+       
+       if ("POST".equalsIgnoreCase(saved.getMethod())) {
+           ByteChunk body = saved.getBody();
+           
+           if (body != null) {
+               request.getCoyoteRequest().action
+                   (ActionCode.ACTION_REQ_SET_BODY_REPLAY, body);
+   
+               // Set content type
+               MessageBytes contentType = MessageBytes.newInstance();
+               
+               // If no content type specified, use default for POST
+               String savedContentType = saved.getContentType();
+               if (savedContentType == null) {
+                   savedContentType = "application/x-www-form-urlencoded";
+               }
+
+               contentType.setString(savedContentType);
+               request.getCoyoteRequest().setContentType(contentType);
+           }
+       }
+       request.getCoyoteRequest().method().setString(saved.getMethod());
+
+       request.getCoyoteRequest().queryString().setString
+           (saved.getQueryString());
+
+       request.getCoyoteRequest().requestURI().setString
+           (saved.getRequestURI());
+       return (true); 
+   }
+
+
+   /**
+    * Save the original request information into our session.
+    *
+    * @param request The request to be saved
+    * @param session The session to contain the saved information
+    * @throws IOException
+    */
+   @SuppressWarnings("unchecked")
+   protected void saveRequest(Request request, Session session)
+       throws IOException {
+
+       // Create and populate a SavedRequest object for this request
+       SavedRequest saved = new SavedRequest();
+       Cookie cookies[] = request.getCookies();
+       if (cookies != null) {
+           for (int i = 0; i < cookies.length; i++)
+               saved.addCookie(cookies[i]);
+       }
+       Enumeration names = request.getHeaderNames();
+       while (names.hasMoreElements()) {
+           String name = (String) names.nextElement();
+           Enumeration values = request.getHeaders(name);
+           while (values.hasMoreElements()) {
+               String value = (String) values.nextElement();
+               saved.addHeader(name, value);
+           }
+       }
+       Enumeration locales = request.getLocales();
+       while (locales.hasMoreElements()) {
+           Locale locale = (Locale) locales.nextElement();
+           saved.addLocale(locale);
+       }
+
+       if ("POST".equalsIgnoreCase(request.getMethod())) {
+           ByteChunk body = new ByteChunk();
+           body.setLimit(request.getConnector().getMaxSavePostSize());
+
+           byte[] buffer = new byte[4096];
+           int bytesRead;
+           InputStream is = request.getInputStream();
+       
+           while ( (bytesRead = is.read(buffer) ) >= 0) {
+               body.append(buffer, 0, bytesRead);
+           }
+           saved.setBody(body);
+           saved.setContentType(request.getContentType());
+       }
+
+       saved.setMethod(request.getMethod());
+       saved.setQueryString(request.getQueryString());
+       saved.setRequestURI(request.getRequestURI());
+
+       // Stash the SavedRequest in our session for later use
+       session.setNote(Constants.FORM_REQUEST_NOTE, saved);
+   }
+
+   /**
+    * Return the request URI (with the corresponding query string, if any)
+    * from the saved request so that we can redirect to it.
+    *
+    * @param session Our current session
+    */
+   protected String savedRequestURL(Session session) 
+   {
+
+       SavedRequest saved =
+           (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
+       if (saved == null)
+           return (null);
+       StringBuffer sb = new StringBuffer(saved.getRequestURI());
+       if (saved.getQueryString() != null) {
+           sb.append('?');
+           sb.append(saved.getQueryString());
+       }
+       return (sb.toString());
+
+   }
+   
+   //Forward Methods
+   /**
+    * Called to forward to the login page
+    * 
+    * @param request Request we are processing
+    * @param response Response we are creating
+    * @param config    Login configuration describing how authentication
+    *              should be performed
+    */
+   protected void forwardToLoginPage(Request request, Response response, LoginConfig config) 
+   {
+       RequestDispatcher disp =
+           context.getServletContext().getRequestDispatcher
+           (config.getLoginPage());
+       try {
+           disp.forward(request.getRequest(), response.getResponse());
+           response.finishResponse();
+       } catch (Throwable t) {
+           log.warn("Unexpected error forwarding to login page", t);
+       }
+   }
+
+
+   /**
+    * Called to forward to the error page
+    * 
+    * @param request Request we are processing
+    * @param response Response we are creating
+    * @param config    Login configuration describing how authentication
+    *              should be performed
+    */
+   protected void forwardToErrorPage(Request request, Response response, LoginConfig config) 
+   {
+       RequestDispatcher disp =
+           context.getServletContext().getRequestDispatcher
+           (config.getErrorPage());
+       try {
+           disp.forward(request.getRequest(), response.getResponse());
+       } catch (Throwable t) {
+           log.warn("Unexpected error forwarding to error page", t);
+       }
+   }
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/SecurityActions.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/SecurityActions.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/SecurityActions.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,70 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi.modules;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * Privileged Blocks
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 8, 2008
+ */
+class SecurityActions
+{
+   static Class<?> loadClass(final String fqn) throws PrivilegedActionException
+   {
+     return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>()
+     {
+        public Class<?> run() throws Exception
+        {
+           ClassLoader tcl = getContextClassLoader();
+           return tcl.loadClass(fqn); 
+        }
+     });  
+   } 
+   
+   static ClassLoader getContextClassLoader()
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+      {
+         public ClassLoader run()
+         {
+            return Thread.currentThread().getContextClassLoader();
+         }
+      });
+   }
+   
+   static void setSystemProperty(final String key, final String value)
+   {
+      AccessController.doPrivileged(new PrivilegedAction<Object>()
+      {
+         public Object run()
+         {
+            System.setProperty(key, value);
+            return null;
+         }
+      });
+   }
+}
\ No newline at end of file

Added: trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/TomcatServerAuthModule.java
===================================================================
--- trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/TomcatServerAuthModule.java	                        (rev 0)
+++ trunk/tomcat/src/main/org/jboss/web/tomcat/security/jaspi/modules/TomcatServerAuthModule.java	2008-10-09 16:48:35 UTC (rev 79305)
@@ -0,0 +1,106 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.web.tomcat.security.jaspi.modules;
+
+import java.security.Principal;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.message.AuthException;
+import javax.security.auth.message.AuthStatus;
+import javax.security.auth.message.MessageInfo;
+import javax.security.auth.message.MessagePolicy;
+import javax.security.auth.message.callback.CallerPrincipalCallback;
+import javax.security.auth.message.callback.PasswordValidationCallback;
+import javax.security.auth.message.module.ServerAuthModule;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.jboss.web.tomcat.security.jaspi.TomcatJASPICallbackHandler;
+
+/**
+ * Base class for Tomcat JSR-196 server auth modules
+ * @author Anil.Saldhana at redhat.com
+ * @since Oct 7, 2008
+ */
+public abstract class TomcatServerAuthModule implements ServerAuthModule
+{
+   protected CallbackHandler callbackHandler;
+   
+   @SuppressWarnings("unchecked")
+   protected Map options;
+   
+   @SuppressWarnings("unchecked")
+   public Class[] getSupportedMessageTypes()
+   { 
+      return new Class[]{Request.class, Response.class, 
+            HttpServletRequest.class,HttpServletResponse.class};
+   }
+
+   @SuppressWarnings("unchecked")
+   public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy,
+         CallbackHandler handler, Map options) throws AuthException
+   {
+      this.callbackHandler = handler;
+      this.options = options;
+   }
+
+   public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException
+   { 
+      Request request = (Request) messageInfo.getRequestMessage();
+      Principal principal = request.getUserPrincipal();
+      if(subject != null)
+         subject.getPrincipals().remove(principal);
+   }
+
+   public abstract AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException;
+
+   public abstract AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, 
+         Subject serviceSubject) throws AuthException;
+   
+   /**
+    * Register with the CallbackHandler
+    * @param userPrincipal
+    * @param username
+    * @param password
+    */
+   protected void registerWithCallbackHandler(Principal userPrincipal, String username,
+         String password)
+   {
+      if(this.callbackHandler instanceof TomcatJASPICallbackHandler)
+      {
+         TomcatJASPICallbackHandler cbh = (TomcatJASPICallbackHandler) callbackHandler;
+         
+         PasswordValidationCallback passwordValidationCallback = 
+            new PasswordValidationCallback(null,username,password.toCharArray());   
+         cbh.setPasswordValidationCallback(passwordValidationCallback);
+         
+         cbh.setCallerPrincipalCallback(new CallerPrincipalCallback(null,userPrincipal));
+      }
+      else
+         throw new RuntimeException(" Unsupported Callback handler "
+               + this.callbackHandler.getClass().getCanonicalName());
+   }
+}




More information about the jboss-cvs-commits mailing list