gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Phone Cards
Promotional Gifts
Compare Prices
GPS
Computer Hardware
Hurricane Shutters
Televisions
Online Education
Find Software
Corporate Gifts
Imprinted Gifts
Boat Donations
Desktop Computers
Baby Photo Contest

 


Hyper-V: The Killer Feature in Windows Server 2008
It's fair to say that while many of the other new features are evolutionary, Hyper-V, by contrast, is revolutionary. Paul Rubens explores Microsoft's big step into virtualization. »

 
Download the Windows Server 2008 Trial
With Windows Server 2008 you can develop, deliver, and manage rich user experiences and applications, provide a secure network infrastructure, and increase technological efficiency and value within your organization. »

 
Reduce Complexity and Costs with Microsoft Identity and Access Solutions
Your organization depends on making digital information accessible to a broad spectrum of users over range of devices and networks. Register now for free Identity and Access Solutions from Microsoft. »

 
Virtualization from the Data Center to the Desktop
Integrated virtualization solutions from Microsoft can help you meet evolving demands more effectively as you transform your IT infrastructure from a cost center to a strategic business asset. »
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Securing J2EE Applications with a Servlet Filter
By Michael Klaene

Go to page: 1  2  Next  

Web applications oftain contain both public and private resources. It is necessary to ensure that those key areas that are restricted to the public remain off limits to even the craftiest of users. This is a common problem and there are many different solutions. In this article, I will show how a Servlet Filter can serve as a simple, unobtrusive agent that will help to safeguard data when developing J2EE web applications.

A Few Options

When discussing the topic of security, there are two main categories to consider. Authentication refers to verifying a certain user is in fact who they say they are. Authentication is handled typically via a username and password login. For most sites, a login page utilizes SSL (Secure Socket Layer) over HTTP (Hyper Text Transfer Protocol). Once authentication is complete, you need to perform authorization. Authorization is concerned with ensuring that what a user accesses conforms to their permission set. In other words, they should only see what they are authorized to see.

Along with many third-party tools, J2EE provides some built-in support for security. In the deployment descriptor of an application (web.xml), for example, you can declaratively configure an application for authentication and authorization (see options available under the <security-constraint> element). For in-depth information on how to use these features, consult the Java Servlet specification. One potential problem with this approach is that implementing some of these features also requires actions specific to a Servlet container, making them not entirely portable. Another option for security is the Java Authentication and Authorization Service (JAAS). JAAS consists of APIs to authenticate and authorize in a pluggable, platform-neutral fashion. JAAS is a bit newer and its use is not as widespread as those previously mentioned.

Of course, coding a solution yourself is always an option too. This is not always desirable, depending on the complexity of the problem you are dealing with. However, if your application has rather unique or complex security requirements, you will probably require a custom solution. Below, I will demonstrate how Java Servlet Filters can help craft a solution that works across Servlet containers.

Filter Review

Servlet Filters were introduced in version 2.3 of the Java Servlet specification. If you are completely new to Filters, I suggest reading about them here. I will attempt a high-level overview now. Read about the Intercepting Filter design pattern to better understand the problem Filters try to address.

A Servlet Filter object implements an interface that specifies three methods: init, doFilter, and destroy. The first and the last allow for custom processing at the beginning and end of the object's life cycle. To enable a Filter to initialize itself, an instance of FilterConfig is passed to its init method. The most important method for a Filter object is doFilter. This is where the Filter does its job. It accepts objects of type ServletRequest and ServletResponse (which usually need to be cast to their HTTP versions: HttpServletRequest and HttpServletReponse), and a FilterChain object that contains a 'chain' of Filters to execute (if any) after the current Filter finishes its work.

So how does a Filter object execute? A Filter is specified in the web.xml file inside the <filter> element, along with a corresponding <filter-mapping> that maps a Filter to a request pattern. When this pattern matches a request URI, doFilter on the Filter object is invoked. This allows you, the developer, to intercept the normal application flow and perform whatever tasks you deem necessary. These tasks commonly include logging, compression of response data, and in our case, enforcing application security.

An Authorization Filter

For the purposes of this article, I will assume that the authentication piece of the puzzle has been solved, either custom either by programming or using the declarative support the Servlet specification provides. I will focus on performing authorization for the application. For this, you will use a Filter object. In fact, a Servlet Filter could help solve the authentication problem as well (and handle other security-related tasks, such as storing number of login attempts, locking accounts, and so forth.).

The fictitious application includes public resources, resources for intranet users, and resources that should be accessed only by an administrator. As a result, you need to intercept requests to verify that a user's role or roles allows them to go where they are attempting to go. The Filter intercepts the requests, then, to achieve a clean separation of concerns, invokes a method on the Java class that actually performs the work. There are three objects to look at—an interface, its default implementation, and a Filter object. You'll start with the interface.

The Java interface used for authorization is called, appropriately, AuthorizationManager.

package examples;

/**
 * Manages authorization to the system.
 *
 * @author Michael Klaene
 */
public interface AuthorizationManager {

     public boolean isUserAuthorized(User user,String uri);

}

AuthorizationManager specifies a lone method, public boolean isUserAuthorized(User user,String uri). Method isUserAuthorized accepts a User object, presumably stored in the current HttpSession, and the request URI. It returns true if that user is authorized to view the resource, false otherwise.

A Servlet Filter, AuthorizationFilter, will obtain a reference to an object of type AuthorizationManager and invoke its method. The resources for users and an administrator have been grouped in a subfolder entitled 'restricted'. The following web.xml entries are required for AuthorizationFilter's doFilter method to be invoked each time a 'restricted' resource is requested:

<!--Servlet Filter that handles site authorization.-->
<filter>
     <filter-name>AuthorizationFilter</filter-name>
     <filter-class>examples.AuthorizationFilter</filter-class>
     <description>This Filter authorizes user access to application
                  components based upon request URI.</description>
     <init-param>
        <param-name>error_page</param-name>
        <param-value>../../error.jsp</param-value>
     </init-param>
</filter>

<filter-mapping>
     <filter-name>AuthorizationFilter</filter-name>
     <url-pattern>/restricted/*</url-pattern>
</filter-mapping>
Note: You are configuring your Filter by using an initialization parameter called 'error-page'. A FilterConfig object provides this value in AuthorizationFilter's init method. It tells the Filter where to redirect authorization failures:
private String errorPage;

/**Filter should be configured with an system error page.*/
public void init (FilterConfig FilterConfig) throws ServletException {
       if (FilterConfig != null) { 
           errorPage = FilterConfig.getInitParameter("error_page");
       }

Here is the code for doFilter:

public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain)
       throws ServletException, IOException {
      if(errorPage == null) {
         returnError(request,response,"AuthorizationFilter not
                     properly configured! Contact Administrator.");
      }

      HttpSession session =
          ((HttpServletRequest)request).getSession(false);
      User currentUser = (User)session.getAttribute("user");

      if (currentUser == null) {
          returnError(request,response,"User does not exist in
                      session!");
      }
      else {
          //Get relevant URI.
          String URI = ((HttpServletRequest)request).getRequestURI();

          //Obtain AuthorizationManager singleton from Spring
          //ApplicationContext.
          ApplicationContext ctx =
              WebApplicationContextUtils.getWebApplicationContext(
              session.getServletContext());
          AuthorizationManager authMgr =
              (AuthorizationManager)ctx.getBean("AuthorizationManager");

          //Invoke AuthorizationManager method to see if user can
          //access resource.
          boolean authorized = authMgr.isUserAuthorized(currentUser,URI);
          if (authorized) {
              chain.doFilter(request,response);
          }
          else {
              returnError(request,response,"User is not authorized
                          to access this area!");
          }
      }
}

The top half of doFilter is concerned with checking that the necessary variables are present. The error page should have been stored upon initialization. Also, in this application, a User object should exist in the current session if authentication was performed. A private utility method (returnError) is used to forward to the designated error page with the relevant error text. The remaining code obtains the current URI requested and passes it, along with the User object, to the isUserAuthorizedMethod on an instance of AuthorizationManager. If authorized, the request is forwarded on (possibly to another Filter, if more than one was mapped to this request).

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Enterprise Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Whitepaper: Embeddable Content Platform for OEM's
Is it time to make your move to the multi-threaded and parallel processing world? Find out!



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES