Google

Friday, October 26, 2007

RESTRICTING ACCESS TO AJAX SERVICES

Mashups are appearing on the web at an extremely fast rate. It's estimated that three new mashups appear on the web each day. As a service provider, you know that exposing your service so that it can be used in mashups can benefit you in a number of ways. Among other things, mashups can advertise the existence of your services to a constantly growing audience. However, there are some things you should consider when you make a service available for mashups. One of them is the possibility of security exposures. You want people to use your service but not abuse it.

If you're a service provider, you can take actions that protect your service such as limiting or restricting access. This article highlights some techniques for restricting access to a service. It then focuses on using API keys, which gives you finer-grained protection than the other techniques covered in this article. It allows you to restrict access to your service to users in specific host domains. You can also use API keys to identify who is using your service or meter usage, that is, regulate how much your service is used during a given period of time. However, the focus of this article is primarily on how to limit or restrict access to your service.

Here are some approaches that you can take to restrict access to your service:

  • Token-Based Restriction
  • Application key-based Restriction
  • Session-based Restriction
  • Content type restriction
  • Authentication-based restriction
  • URL based API key restriction

JAVA BEANS

Rapid application development tools are great. Visual Basic, Delphi, etc. are great at cutting development time for complex applications through their use of reusable components.

Reusable components (I will refer to them as "controls" from here on) are simply pre-built pieces of programming code designed to perform a specific function. When designing an application in a visual environment, controls can be quickly dropped into the design, and modified to fit the task at hand. Most of the controls you'll find are designed to handle such tasks as pushbuttons, menus, text labels, and so forth. As a developer, you only need to write code to "glue" them into your application, and develop the interactions between controls.

Recently, programmers have been searching for some way to create and reuse components in the Java language. Java holds great promise, but the early releases lacked any method for creating reusable controls, and thus caused extended development times for applications. Sun Microsystems, the creators of the Java language, have at last recognized this need, and have released the Java Beans Component Architecture. Java Beans are, quite simply, reusable controls written in Java, for Java application development.

Beans are "capsules" of code, each designed for a specific purpose. The advantage of Java Beans over standard programming controls is that Beans are independent. They are not specific to operating systems or development environments. A Bean created in one development environment can be easily copied and modified by another. This allows Java Beans greater flexibility in enterprise computing, as components are easily shared between developers.

Java Beans are best put to use by visual developers. In a visual design environment (for example, Symantec's Visual Cafe Pro, this author's current tool of choice), an application interface is developed on a "form" or client window. A toolbox contains all the controls (Beans) which are dropped onto the form through simple drag and drop procedures. As the controls are dropped onto the form, the development environment grinds out the necessary code, When the interface is finished, the developer can set about creating the actual interactions between controls and the application as a whole. An exciting concept behind Beans springs from the fact that an application created in Java can be used as a Bean, which can be used to build other applications. As you can imagine, this circle of application to Bean and back can make developing large-scale applications much easier.

Some may wonder why anyone would use a Bean over a Java Class file. The strongest argument for a Bean over a Class is that Beans support introspection. That is, they allow the development environment to analyze the Bean, determine its properties and methods, and manipulate the Bean at design time instead of at run time.

The newest use of Beans is to create a bridge between Java and ActiveX. Several software companies are working on methods of quickly converting ActiveX controls to Java Beans (IBM's Visual Age, for example, is leading the pack in this area). Whereas Microsoft hoped to encompass Java into ActiveX, it appears that developers have different ideas and are churning out a wide variety of conversion tools to pull ActiveX into Java.

Java Beans are not a cure for all your programming ills, though. Beans are great for developing interfaces and basic applications, but for working with JDBC and SQL, text-based hand coding is your best bet.

If you're a visual developer looking to migrate to Java, you'll find that Java Beans will make the transition much easier. With Java Beans, Sun is proving that Java is poised to grow and become a powerful force in application development.

For more information about Java and Beans on the Web, try:
http://java.sun.com
http://www.javasoft.com
http://splash.java.com
http://www.developer.com
http://www.javology.com/javology

Applets - An applet is a mini-application developed in the Java language. Applets are commonly downloaded from the Internet and run on the user's machine. Lately, even full-scale Java applications have been referred to as applets.

IDE - Integrated Development Environment. Usually a visual-style programming application. Common IDE's include Visual Basic, Delphi, and Symantec's Visual Café

Java - A programming language, developed by Sun Microsystems, which is designed to be run on any type of operating system. Applications developed in Java are "Written once, run anywhere".

JDBC - Java Database Connectivity. This allows Java applets/applications to read/write/modify data in any of the supported JDBC database formats.
SQL - Structured Query Language (or Standard Query Language, depending on who you ask). SQL is a language used to "ask questions of" a database. Through SQL, an application makes specific requests for information, and the database relays that information back to the application.

NAMED PARAMETERS FOR PREPARED STATEMENT

In past if you have worked with JDBC than you may know that keeping track of the indices of PreparedStatement is very difficult for larger queries having tens of parameters.

If you needs to insert or delete a parameter in the middle of a query, you must renumber all the parameters following it.

To make writing parameterized query easier, Adam has created NamedParameterStatement.
With NamedParameterStatement, instead of question marks, parameters are represented as a colon followed by an identifier.

So developer don't need to remember index of a parameters, insted parameters can be set using identifier.

Internally NamedParameterStatement uses PreparedStatement and replaces parameter identifiers with question marks.

Here is an example of how NamedParameterStatement can make developers life easier.


String query = "select * from users where userid = :userid;
NamedParameterStatement p = new NamedParameterStatement(con, query);
p.setString("userid", userid);

Look at following insert query.

StringBuffer query = new StringBuffer("INSERT INTO users (userid, first_name, last_name, street, city, country, zip_code));
query.append("VALUES (:userid, :fname, :lname, :street, :city, :country)");
NamedParameterStatement statement= new NamedParameterStatement(conn,query.toString());
statement.setString("userid", userid);
statement.setString("fname", fname );
statement.setString("lname", ;name );
statement.setString("street", street );
statement.setString("city", city);
statement.setString("country", country);
statement.executeUpdate();

Now if you want to insert a new parameter 'middle_initial' at third position, it can be done as in the following.

StringBuffer query = new StringBuffer("INSERT INTO users (userid, first_name,middle_initial, last_name, street, city,country, zip_code));
query.append("VALUES (:userid, :fname, :middleinitial, :lname, :street, :city, :country)");
NamedParameterStatement statement= new NamedParameterStatement(conn,query.toString());
statement.setString("userid", userID);
statement.setString("fname", firstName);
statement.setString("lname", lastName);
statement.setString("street", street );
statement.setString("city", city);
statement.setString("country", country);
statement.setString("middleinitial", middleInitial);
statement.executeUpdate();

You don't need to renumber parameters following middle_initial, insted new parameter is added at the end.

This code is not only flexible but it is more understandable also.

A Command pattern for Ajax?

In the canonical example, the Gand of Four Command pattern is used by a toolkit developer to enable future users to specify actions within the toolkit. Not knowing how the toolkit will be used, the developer codes to an interface, leaving the implementation details abstract.

The average enterprise Web application involves a similar scenario, where one person or group provides the tools to another. Although the typical Web application probably doesn't need to provide such complete autonomy between teams, other factors at work in a JSF-Ajax call suggest the use of the Command pattern; namely the layered architecture, the intermediary of HTTP, and JSF's component model.

Now, let's say you're working on a Web application where you need to do the following:

  1. Handle commands arriving as Ajax requests without isolating the logic in a component.
  2. Make it easy to add new commands.
  3. Delegate the business logic to the business layer.

We'll start by taking a look at how you would set up the server side of the request, based on the AjaxCommand strategy. After that we'll look at the front-end design, and I'll conclude by comparing the original Command pattern with the AjaxCommand variation.

THE AJAX COMMAND STRATEGY FOR JSF

As Java Server Faces continues to mature and its component libraries grow more robust, it becomes an ever more compelling option for enterprise Web application development. Ajax has passed the stage of being the hot new thing to become an expected aspect of competitive Web applications. Marrying the two isn't necessarily difficult, but it does present some interesting puzzles. In this article, Java developer Matthew Tyson tackles one such puzzle: how to handle a single (or similar) Ajax request action across multiple JSF components, without duplicating code in the components.

I recently encountered a problem at work that had me delving into the Gang of four design patterns for a solution. I was working on a tree component that rendered its nodes according to nested facets. The user could delete a node by clicking on a Delete button or by right-clicking and selecting Delete. The delete was to be carried out via an Ajax call.

Coding all this was relatively easy, but for one problem: I needed to delete objects outside the tree, for instance, from the item detail page and from the toolbar. I didn't want to embed the deletion request logic in the tree component's renderer. I needed the logic to be accessible anywhere; from links, buttons and images, anything that could handle an onClick.

Describing my solution to a colleague the next day took quite a while. Once I had successfully conveyed the design, my coworker paused for a moment and said, "Oh, you mean it's a Command?"

The Command pattern is a convenient way to express the intention of the AjaxCommand strategy, though there are some differences. I'll focus on the AjaxCommand strategy in this article, but use the Command pattern as a point of reference.

Note that I assume you are familiar with JSF and Ajax development in general. I've used the Dojo Library for my example, but the idea applies regardless of how you accomplish your Ajax calls.

LAUNCH JAVA APPLICATIONS FROM ASSEMBLY LANGUAGE PROGRAMS

Java Native Interface (JNI) is a mechanism that can be used to establish communication between native language programs and the Java virtual machine. The documentation for JNI and the technical literature on JNI deal extensively with interactions between the JVM and C/C++ code. The Java SDK even provides a utility to generate a header file to facilitate calling C/C++ programs from Java code. However, there is hardly any mention of Java and assembly earlier language showed how assembly language programs can be called from Java applications. Here I deal with the technique for invoking Java programs from an ASM process through a demo application that calls a Java method from assembly language code. The Java method brings up a Swing JDialog to show that it has, indeed, been launched.

PREVENTING THREAD PROBLEMS WITH YOUR SINGLETON

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}