HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Fitting the Pieces into the Enterprise Java Jigsaw, by Tony Loton

The choices can be overwhelming for a development team embarking on an Enterprise Java project. You've read the books, attended the classes, and now know the individual Java technologies pretty well, but how do you choose between them? Should your project be based on servlets, applets, EJBs, any two, or all three?

In this series I try to show how each technology can be used as part of an enterprise application to fit the pieces into the Enterprise Java jigsaw. For a practical perspective, I'll present an example that starts with a single Java servlet and finishes with a small working application that's composed of applets, servlets, EJB, and JDBC, and has a basic access control mechanism. My intention is not to provide a comprehensive tutorial on any individual technology, but to give just enough information to demonstrate some of the possible combinations.

The emphasis will be placed firmly on the three major architectures - applet, servlet, and EJB - that provide three alternative styles for enterprise application development. I'll mention some of the other J2EE technologies - such as XML and JSP - in passing, but not in detail.

The code listings highlight the important techniques, and some routine statements were removed for clarity. Although you can't necessarily run these code snippets as presented, rest assured they're all based on applications that are known to work.

HTTP Authentication and a Login Servlet
In this article I start with a single servlet and use this as the basis for a simple but effective access control system based on HTTP authorization and servlet session tracking. By the end of this article, the security framework for my application will be in place and I'll have covered some simple JDBC along the way.

The access control solution that I offer is intended for use with in-house intranet applications with security requirements that are limited to authentication (asking a user to log in) and authorization (propagating the user's identity so application components can allow or deny their functionality to the user). If you're developing Internet applications that handle sensitive data, such as credit card numbers, you'll also need to think about encryption.

Getting a user to log in by supplying a username and password is quite straightforward with HTTP authentication. Every application server that I've used allows you to flag the URL path to any resource as being protected. When a user tries to access the HTML page or servlet that the URL represents, the server provokes the user's browser into displaying an authentication dialog box (see Figure 1). The target page will be displayed or the servlet executed only if the user supplies a valid username as the password. This is completely automatic; all you need to do is provide the server with a list of valid usernames and passwords.

Figure 1
Figure  1:

Some servers allow you to use the same method but vary the way the authentication is actually done, maybe via an HTML form or using certificates. Bear that in mind when you build a real system; however, for my example I'll stick with the basic HTTP authentication.

For authentication I'll use a servlet as the protected resource and call it LoginServlet. When the user tries to run the LoginServlet via its URL, he or she will be prompted to authenticate. If authentication succeeds, the servlet will be executed. Listing 1 shows an extract of the code for the LoginServlet, which possesses no code for authentication since this is handled automatically by the application server and Web browser.

First I get the remote user name from the HttpRequest. If the user hasn't authenticated because a valid username and password were not supplied, or because I forgot to protect the servlet URL in the first place, the getRemoteUser() method returns null. This means that authorization (propagating the user identity to allow or deny certain functions) won't work without prior authentication, which is exactly what we want.

Next I take the current HttpSession, which provides a context for me to pass the user identity and any other information from this servlet to other servlets that comprise the application. Any Web server supporting the servlet API will provide a session-tracking mechanism, probably via cookies, that supports an HttpSession context for each remote user.

Finally I write out an error message or a link to a user application as the HTML response, depending on the success or failure of the authentication. In the latter case I also write the user name into the HttpSession for future servlets to pick up.

An Application Servlet
The "Click here to run an application" link shown in the last statement of Listing 1 points to another servlet that I've created called AppServlet, which acts as a real application the user can run. An extract of the code is provided in Listing 2.

First I take the current HttpSession for the user, then extract the user's identity, which was stored by the LoginServlet, from the session. If all I wanted to know was the username, I could have called req.getRemoteUser() instead, but the point of using the HttpSession is to allow more complex information to be propagated - maybe a list of the user's access rights or presentation preferences, either of which may have been determined initially by the LoginServlet. Based on the user credentials, in this case his or her name, the application servlet does one of three things as indicated by the comments.

Because the user entry in the HttpSession will be null unless the LoginServlet has been visited, there's no need to make AppServlet or any other application servlet a protected resource, thus reducing the amount of configuration that's needed each time a new application is added. Another benefit is that the user's first port of call must be the LoginServlet, so you have a single point at which you can implement some application-independent initialization - maybe opening a database connection for the lifetime of the user's session, or preventing people from logging in at all during system downtime.

So far it appears as if this idea is limited to servlet-based applications, doesn't it? Well, you can also apply it to applications based on Java applets as long as you invoke each applet via a corresponding servlet rather than from a static HTML page. Each applet should have a servlet that creates the HTML containing the <applet> tag only if the servlet decides that the user is authenticated and authorized for that applet. There will be more about applets in my second article.

JDBC and a Menu of HTML Links
Being authorized to run only one application is not particularly useful, so I'll now beef up the LoginServlet a bit to display a list of options available to each user upon logging in. These authorized options are stored in a database table called useroptions, and I use JDBC to extract the relevant rows for the current user. Each option will be displayed as an HTML link (see Listing 3).

You might have noticed that I'm using JNDI to look up the name of a data source to use for my JDBC connection. This provides a level of indirection that allows the specification of the actual JDBC connection string to be deferred until deployment. Depending on your requirements and the application server you're using, you might want to connect using the more traditional approach, for example (for Oracle):

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(COMMUNITY=tcp)
(PROTOCOL=TCP)(Host=123.456.789.10)(Port=1521)))(CONNECT_DATA=(SID=MYDB)))",
"scott", "tiger");

On the presentation side, at this point I'll add an initial HTML page that has a frame for the login page (and options menu) and a separate frame for the initial splash screen and subsequent content.

Figure 2 demonstrates that when "bill" logs in, he sees two authorized options - getTasks and transferTasks.

Figure 2
Figure  2:

The underlying database table contains the data shown in Table 1, so when another user, "ben," logs in he sees only the getTasks option. Take my word for it.

Table 1
Table  1:

Conclusion
I've implemented these ideas with the J2EE Reference Implementation and WebLogic Server, and something similar in the distant past with Oracle Application Server and Java Web Server. Possibly, it represents the simplest approach to providing an access control infrastructure for intranet applications, taking advantage of the mechanisms already provided by the application server and adding just one additional component, the Login- Servlet.

Every one of the application servers I've mentioned supports HTTP authentication and session tracking via cookies. One difference you might need to be aware of, however, is that while session tracking across servlets seems to work irrespective of the URL context in WebLogic, the J2EE demands that all servlets sharing the same HttpSession must be deployed in the same Web archive (WAR) file, and hence share the same URL context.

Finally, with the basic security mechanism in place and a promise that it can be used with applets as well as servlets, tune in next time to find out how to incorporate one or more applets into the architecture and set up a communication channel between the servlets and the applets that comprise the enhanced application.

Author Bio
Tony Loton works through his company - LOTONtec Limited (www.lotontech.com) - as an independent consultant, course instructor, and technical author. He's spent the past 10 years in IT, the last five devoted almost exclusively to Java, UML, and related technologies. He holds a degree in computer science and management. tony@lotontech.com

	


Listing 1

public class LoginServlet extends HttpServlet
{
 public void doGet(HttpServletRequest req
 , HttpServletResponse res) throws IOException
 {
   // -- find out who the remote user is --
   String user=req.getRemoteUser();


   // -- get the current http session --
   HttpSession session=req.getSession(true);


   res.setContentType("text/html");
   PrintWriter out = res.getWriter();


   if (user==null)
   {
     // -- authentication failed, show error --
   }
   else
   {
     // -- save user name for future servlets --
     session.setAttribute("user", user);


     // -- respond with HTML including --
     // -- this link to an application --
     out.println("<a href='AppPage'>Click here to run an application.</a>");
   }
 }
}



Listing 2

public class AppServlet extends HttpServlet
{
 public void doGet(HttpServletRequest req
 , HttpServletResponse res) throws IOException
 {
   // -- get the current http session -
   HttpSession session=req.getSession(true);


   res.setContentType("text/html");
   PrintWriter out = res.getWriter();


   // -- get the current user --
   String user=(String)
    session.getAttribute("user");


   if (user==null)
   {
     // -- not authenticated, show message --
   }
   else if (user.equals("bill"))


   {
     // -- we like this user, so run the app --
   }
   else
   {
     // -- authenticated, not allowed this app --
   }
 }
}



Listing 3

public void doGet(HttpServletRequest req
, HttpServletResponse res) throws IOException
{
 // -- find out who the remote user is --
 String user=req.getRemoteUser();


 // -- get the current http session --
 HttpSession session=req.getSession(true);


 res.setContentType("text/html");
 PrintWriter out = res.getWriter();


 if (user==null)
 {
   // -- print the unauthorized message here --
 }
 else
 {
   // -- save the user name for future servlets --
   session.setAttribute("user", user);


   out.println("<html>");
   out.println("<head><title>LoginServlet</title></head>");
   out.println("<body>");


   Vector options=new Vector();


   try
   {
     // -- get DB connection from a datasource --
     InitialContext ic = new InitialContext();


     DataSource ds = (DataSource)
      ic.lookup("java:comp/env/jdbc/LOTONtech");


     Connection con = ds.getConnection();


     // -- select user's menu options --
     Statement st=con.createStatement();


     ResultSet results=st.executeQuery
      ("SELECT username, useroption
      FROM useroptions WHERE username='"+user+"'");


     while (results.next())
     {
       String useroption=results.getString(2);
       options.addElement(useroption);
     }
   }
   catch (Exception e)
   {
     out.println("ERROR: Connecting to database!");
   }


   //-- write the options out as html --
   out.println("Welcome "+user+", choose an option:");


   for (int opNum=0; opNum<options.size(); opNum++)
   {
     String thisOption=(String)
      options.elementAt(opNum);


     out.println("<a href='"+thisOption
      +"' target='main'><font size=3><b>"
      +thisOption+"</b></font></a>  ");
   }


   out.println("</body>");
   out.println("</html>");
 }




  
 
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: info@sys-con.com

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.