Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT

Java IoT: Article

Enterprise Java

Enterprise Java

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.

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 get- RemoteUser() 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 Log- inServlet, 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.

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.

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.

More Stories By Tony Loton

Tony Loton works through his company - LOTONtech Limited (www.lotontech.com) - as an independent consultant, course instructor, and technical author. He has a degree in computer science and management and has spent 10 years in I.T. The last five years have been devoted almost exclusively to Java, UML, and related technologies.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Scala Hosting is trusted by 50 000 customers from 120 countries and hosting 700 000+ websites. The company has local presence in the United States and Europe and runs an internal R&D department which focuses on changing the status quo in the web hosting industry. Imagine every website owner running their online business on a fully managed cloud VPS platform at an affordable price that's very close to the price of shared hosting. The efforts of the R&D department in the last 3 years made that pos...