KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > web > test > FormAuthUnitTestCase


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.web.test;
23
24 import java.net.HttpURLConnection JavaDoc;
25 import java.util.List JavaDoc;
26
27 import javax.management.MBeanServerConnection JavaDoc;
28 import javax.management.MBeanServerInvocationHandler JavaDoc;
29 import javax.management.ObjectName JavaDoc;
30
31 import org.apache.commons.httpclient.Cookie;
32 import org.apache.commons.httpclient.Header;
33 import org.apache.commons.httpclient.HttpClient;
34 import org.apache.commons.httpclient.HttpState;
35 import org.apache.commons.httpclient.methods.PostMethod;
36 import org.apache.commons.httpclient.methods.GetMethod;
37 import org.jboss.test.JBossTestCase;
38 import org.jboss.test.JBossTestSetup;
39 import org.jboss.security.plugins.JaasSecurityManagerServiceMBean;
40 import junit.framework.Test;
41 import junit.framework.TestSuite;
42
43 /** Tests of form authentication
44  *
45  * @author Scott.Stark@jboss.org
46  * @version $Revision: 39632 $
47  */

48 public class FormAuthUnitTestCase extends JBossTestCase
49 {
50    private String JavaDoc baseURLNoAuth = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + "/";
51    private HttpClient httpConn = new HttpClient();
52
53    public FormAuthUnitTestCase(String JavaDoc name)
54    {
55       super(name);
56    }
57
58    /** Test form authentication of a secured servlet
59     *
60     * @throws Exception
61     */

62    public void testFormAuth() throws Exception JavaDoc
63    {
64       log.info("+++ testFormAuth");
65       doSecureGetWithLogin("form-auth/restricted/SecuredServlet");
66       /* Access the resource without attempting a login to validate that the
67          session is valid and that any caching on the server is working as
68          expected.
69       */

70       doSecureGet("form-auth/restricted/SecuredServlet");
71    }
72
73    /**
74     * Test that a bad login is redirected to the errors.jsp and that the
75     * session j_exception is not null.
76     *
77     * @throws Exception
78     */

79    public void testFormAuthException() throws Exception JavaDoc
80    {
81       log.info("+++ testFormAuthException");
82       GetMethod indexGet = new GetMethod(baseURLNoAuth+"form-auth/restricted/SecuredServlet");
83       int responseCode = httpConn.executeMethod(indexGet);
84       String JavaDoc body = indexGet.getResponseBodyAsString();
85       assertTrue("Get OK("+responseCode+")", responseCode == HttpURLConnection.HTTP_OK);
86       assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
87
88       HttpState state = httpConn.getState();
89       Cookie[] cookies = state.getCookies();
90       String JavaDoc sessionID = null;
91       for(int c = 0; c < cookies.length; c ++)
92       {
93          Cookie k = cookies[c];
94          if( k.getName().equalsIgnoreCase("JSESSIONID") )
95             sessionID = k.getValue();
96       }
97       getLog().debug("Saw JSESSIONID="+sessionID);
98
99       // Submit the login form
100
PostMethod formPost = new PostMethod(baseURLNoAuth+"form-auth/j_security_check");
101       formPost.addRequestHeader("Referer", baseURLNoAuth+"form-auth/restricted/login.html");
102       formPost.addParameter("j_username", "baduser");
103       formPost.addParameter("j_password", "badpass");
104       responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
105          formPost, state);
106       String JavaDoc response = formPost.getStatusText();
107       log.debug("responseCode="+responseCode+", response="+response);
108       Header jex = formPost.getResponseHeader("X-JException");
109       log.debug("Saw X-JException, "+jex);
110       assertNotNull("X-JException != null", jex);
111    }
112
113    /** Test form authentication of a secured servlet and validate that there is
114     * a SecurityAssociation setting Subject.
115     *
116     * @throws Exception
117     */

118    public void testFormAuthSubject() throws Exception JavaDoc
119    {
120       log.info("+++ testFormAuthSubject");
121       // Start by accessing the secured index.html of war1
122
HttpClient httpConn = new HttpClient();
123       GetMethod indexGet = new GetMethod(baseURLNoAuth+"form-auth/restricted/SecuredServlet");
124       indexGet.setQueryString("validateSubject=true");
125       int responseCode = httpConn.executeMethod(indexGet);
126       String JavaDoc body = indexGet.getResponseBodyAsString();
127       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
128       assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
129
130       HttpState state = httpConn.getState();
131       Cookie[] cookies = state.getCookies();
132       String JavaDoc sessionID = null;
133       for(int c = 0; c < cookies.length; c ++)
134       {
135          Cookie k = cookies[c];
136          if( k.getName().equalsIgnoreCase("JSESSIONID") )
137             sessionID = k.getValue();
138       }
139       getLog().debug("Saw JSESSIONID="+sessionID);
140
141       // Submit the login form
142
PostMethod formPost = new PostMethod(baseURLNoAuth+"form-auth/j_security_check");
143       formPost.addRequestHeader("Referer", baseURLNoAuth+"form-auth/restricted/login.html");
144       formPost.addParameter("j_username", "jduke");
145       formPost.addParameter("j_password", "theduke");
146       responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
147          formPost, state);
148       String JavaDoc response = formPost.getStatusText();
149       log.debug("responseCode="+responseCode+", response="+response);
150       assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
151
152       // Follow the redirect to the SecureServlet
153
Header location = formPost.getResponseHeader("Location");
154       String JavaDoc indexURI = location.getValue();
155       GetMethod war1Index = new GetMethod(indexURI);
156       responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(),
157          war1Index, state);
158       response = war1Index.getStatusText();
159       log.debug("responseCode="+responseCode+", response="+response);
160       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
161       body = war1Index.getResponseBodyAsString();
162       if( body.indexOf("j_security_check") > 0 )
163          fail("get of "+indexURI+" redirected to login page");
164    }
165
166    /** Test that a post from an unsecured form to a secured servlet does not
167     * loose its data during the redirct to the form login.
168     *
169     * @throws Exception
170     */

171    public void testPostDataFormAuth() throws Exception JavaDoc
172    {
173       log.info("+++ testPostDataFormAuth");
174       // Start by accessing the secured index.html of war1
175
HttpClient httpConn = new HttpClient();
176       GetMethod indexGet = new GetMethod(baseURLNoAuth+"form-auth/unsecure_form.html");
177       int responseCode = httpConn.executeMethod(indexGet);
178       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
179       // Submit the form to /restricted/SecuredPostServlet
180
PostMethod servletPost = new PostMethod(baseURLNoAuth+"form-auth/restricted/SecuredPostServlet");
181       servletPost.addParameter("checkParam", "123456");
182       responseCode = httpConn.executeMethod(servletPost);
183
184       String JavaDoc body = servletPost.getResponseBodyAsString();
185       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
186       assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
187
188       HttpState state = httpConn.getState();
189       Cookie[] cookies = state.getCookies();
190       String JavaDoc sessionID = null;
191       for(int c = 0; c < cookies.length; c ++)
192       {
193          Cookie k = cookies[c];
194          if( k.getName().equalsIgnoreCase("JSESSIONID") )
195             sessionID = k.getValue();
196       }
197       getLog().debug("Saw JSESSIONID="+sessionID);
198       // Submit the login form
199
PostMethod formPost = new PostMethod(baseURLNoAuth+"form-auth/j_security_check");
200       formPost.addRequestHeader("Referer", baseURLNoAuth+"form-auth/unsecure_form.html");
201       formPost.addParameter("j_username", "jduke");
202       formPost.addParameter("j_password", "theduke");
203       responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
204          formPost, state);
205       String JavaDoc response = formPost.getStatusText();
206       getLog().debug("responseCode="+responseCode+", response="+response);
207       assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
208
209       // Follow the redirect to the SecureServlet
210
Header location = formPost.getResponseHeader("Location");
211       String JavaDoc indexURI = location.getValue();
212       GetMethod war1Index = new GetMethod(indexURI);
213       responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(),
214          war1Index, state);
215       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
216       body = war1Index.getResponseBodyAsString();
217       if( body.indexOf("j_security_check") > 0 )
218          fail("get of "+indexURI+" redirected to login page");
219    }
220
221    /** Test that the war which uses <security-domain flushOnSessionInvalidation="true">
222     * in the jboss-web.xml does not have any jaas security domain cache entries
223     * after the web session has been invalidated.
224     */

225    public void testFlushOnSessionInvalidation() throws Exception JavaDoc
226    {
227       log.info("+++ testFlushOnSessionInvalidation");
228       MBeanServerConnection JavaDoc conn = (MBeanServerConnection JavaDoc) getServer();
229       ObjectName JavaDoc name = new ObjectName JavaDoc("jboss.security:service=JaasSecurityManager");
230       JaasSecurityManagerServiceMBean secMgrService = (JaasSecurityManagerServiceMBean)
231          MBeanServerInvocationHandler.newProxyInstance(conn, name, JaasSecurityManagerServiceMBean.class, false);
232
233       // Access a secured servlet to create a session and jaas cache entry
234
doSecureGetWithLogin("form-auth/restricted/SecuredServlet");
235
236       // Validate that the jaas cache has 1 principal
237
List JavaDoc principals = secMgrService.getAuthenticationCachePrincipals("jbossweb-form-auth");
238       assertTrue("jbossweb-form-auth has one principal", principals.size() == 1);
239
240       // Logout to clear the cache
241
doSecureGet("form-auth/Logout");
242       principals = secMgrService.getAuthenticationCachePrincipals("jbossweb-form-auth");
243       log.info("jbossweb-form-auth principals = "+principals);
244       assertTrue("jbossweb-form-auth has no cache principals", principals.size() == 0);
245    }
246
247    public PostMethod doSecureGetWithLogin(String JavaDoc path) throws Exception JavaDoc
248    {
249       return doSecureGetWithLogin(path, "jduke", "theduke");
250    }
251    public PostMethod doSecureGetWithLogin(String JavaDoc path, String JavaDoc username, String JavaDoc password)
252       throws Exception JavaDoc
253    {
254       GetMethod indexGet = new GetMethod(baseURLNoAuth+path);
255       int responseCode = httpConn.executeMethod(indexGet);
256       String JavaDoc body = indexGet.getResponseBodyAsString();
257       assertTrue("Get OK("+responseCode+")", responseCode == HttpURLConnection.HTTP_OK);
258       assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0 );
259
260       HttpState state = httpConn.getState();
261       Cookie[] cookies = state.getCookies();
262       String JavaDoc sessionID = null;
263       for(int c = 0; c < cookies.length; c ++)
264       {
265          Cookie k = cookies[c];
266          if( k.getName().equalsIgnoreCase("JSESSIONID") )
267             sessionID = k.getValue();
268       }
269       getLog().debug("Saw JSESSIONID="+sessionID);
270
271       // Submit the login form
272
PostMethod formPost = new PostMethod(baseURLNoAuth+"form-auth/j_security_check");
273       formPost.addRequestHeader("Referer", baseURLNoAuth+"form-auth/restricted/login.html");
274       formPost.addParameter("j_username", username);
275       formPost.addParameter("j_password", password);
276       responseCode = httpConn.executeMethod(formPost.getHostConfiguration(),
277          formPost, state);
278       String JavaDoc response = formPost.getStatusText();
279       log.debug("responseCode="+responseCode+", response="+response);
280       assertTrue("Saw HTTP_MOVED_TEMP", responseCode == HttpURLConnection.HTTP_MOVED_TEMP);
281
282       // Follow the redirect to the SecureServlet
283
Header location = formPost.getResponseHeader("Location");
284       String JavaDoc indexURI = location.getValue();
285       GetMethod war1Index = new GetMethod(indexURI);
286       responseCode = httpConn.executeMethod(war1Index.getHostConfiguration(),
287          war1Index, state);
288       response = war1Index.getStatusText();
289       log.debug("responseCode="+responseCode+", response="+response);
290       assertTrue("Get OK", responseCode == HttpURLConnection.HTTP_OK);
291       body = war1Index.getResponseBodyAsString();
292       if( body.indexOf("j_security_check") > 0 )
293          fail("get of "+indexURI+" redirected to login page");
294       return formPost;
295    }
296    public void doSecureGet(String JavaDoc path) throws Exception JavaDoc
297    {
298       HttpState state = httpConn.getState();
299       Cookie[] cookies = state.getCookies();
300       String JavaDoc sessionID = null;
301       for(int c = 0; c < cookies.length; c ++)
302       {
303          Cookie k = cookies[c];
304          if( k.getName().equalsIgnoreCase("JSESSIONID") )
305             sessionID = k.getValue();
306       }
307       getLog().debug("Saw JSESSIONID="+sessionID);
308
309       // Submit the login form
310
GetMethod indexGet = new GetMethod(baseURLNoAuth+path);
311       int responseCode = httpConn.executeMethod(indexGet.getHostConfiguration(),
312          indexGet, state);
313       assertTrue("Get OK("+responseCode+")", responseCode == HttpURLConnection.HTTP_OK);
314    }
315
316    /** One time setup for all SingleSignOnUnitTestCase unit tests
317     */

318    public static Test suite() throws Exception JavaDoc
319    {
320       TestSuite suite = new TestSuite();
321       suite.addTest(new TestSuite(FormAuthUnitTestCase.class));
322
323       // Create an initializer for the test suite
324
Test wrapper = new JBossTestSetup(suite)
325       {
326          protected void setUp() throws Exception JavaDoc
327          {
328             super.setUp();
329             deploy("form-auth.ear");
330             // Make sure the security cache is clear
331
flushAuthCache();
332             //Make sure the ExtendedFormAuthenticator is registered in tomcat
333
String JavaDoc oname = "jboss.web:host="+getServerHost()+",name=ExtendedFormAuthenticator,path=/form-auth,type=Valve";
334             ObjectName JavaDoc formAuth = new ObjectName JavaDoc(oname);
335             //We have a form-auth war with FORM authenticator and that is not overriden at the webapp level
336
assertNotNull("Authenticator for FORM on host=localhost exists?", getServer().getObjectInstance(formAuth));
337          
338          }
339          protected void tearDown() throws Exception JavaDoc
340          {
341             undeploy("form-auth.ear");
342             super.tearDown();
343          }
344       };
345       return wrapper;
346    }
347 }
348
Popular Tags