Securing Cactus Tests

Problem

You want to test a servlet that depends on an authenticated user.

Solution

Configure your web application to handle BASIC authentication and use Cactus to automatically create an authenticated user.

Discussion

Testing server-side code is challenging by itself. Throw in server-side code that relies on an authenticated user, and the challenge grows. Cactus provides a way to test server-side code that relies on an authenticated user—by creating a user for you.[40]

If your servlet or filter uses the following methods then you need Cactus to create an authenticated user:

  • HttpServletRequest.getRemoteUser( )

  • HttpServletRequest.getUserPrincipal( )

  • HttpServletRequest.isUserInRole(String)

If your web application requires an authenticated user, your web application must be secured. In the deployment descriptor, you must declare the URL patterns to secure and which logical roles are allowed. Example 7-15 shows how this is done.

Example 7-15. Securing a web application

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 
  <!-- other elements left out for brevity -->

  <!-- URL pattern not secured -->
  <filter>
      <filter-name>FilterRedirector</filter-name>
      <filter-class>
        org.apache.cactus.server.FilterTestRedirector
      </filter-class>
  </filter>

  <!-- URL pattern secured --> <filter> <filter-name>SecureFilterRedirector</filter-name> <filter-class> org.apache.cactus.server.FilterTestRedirector ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.