openid-1

Dummies Guide to GWT and OpenID – with example code

Once (?) in awhile, we developers browse the web for some quick and dirty solutions to some of our coding problems (sometimes not even problems, right?). This is another of those days, everything was going fine on this project I am currently working on. This is not a social networking sites but a site for sharing and comunicating (how I missed the days of the chatrooms) similar in many aspect to Digg and DZone but which also allows users to communicate in realtime and leave comments. So the back-end was sort of completed but so now time to focus on the user registration.

The sites needed to be open and avoid repeatitive tasks such registering users. The way forward was to implement some authentication to allow users to register with some sort of universally accessible ID (or sort of). Facebook Connect, OpenSocial and Google Accounts have their advantages but to me personally; the disadvantages outweight the pros. These are some of the disadvantages of those platform:

  1. Facebook is a popular site hence is its platform, Facebook Connect, in mostly Europe and America but not everybody in Europe and America have a Facebook account.
  2. OpenSocial, when it comes to single logon, has more advantages than Facebook. I supposed that if we do take into consideration all the OpenSocial sites, we might have apossible larger user based than supporting Facebook alone. Even that was too limited.
  3. Google Accounts, one thing Google does not advertise its user base. I could be wrong but do anybody actually knows how many people uses the various Google services (excluding search). Google has the same disadvantages as Facebook.

Enter OpenID. OpenID has been around longer than most Internet-based decentralised authentication platform. The beauty of this platform is that it also supported by most (if not all) large site on the Internet. From AOL, BBC, CNN to YAHOO and ZIMBRA, as I said most sites (based on the alphabet) support OpenID, check the OpenID Directory. It was recently announced that OpenID has reached 1Billion enabled accounts (read here). Based on those figures, I decided that OpenID for now was the authentication choice for this application. I will not be discussing any security issues in this entry, there are plenty of resources available on the Internet for that.

OK, so I am a Java developer and I am developing the front-end using GWT and Java on the server-side. I searched on the Internet for solutions on how to implement the authentication as GWT RPC are different to normal servlet call. I spent more time reading about the OpenID specification and implementations examples on the Internet. I have to admit that some of tutorials that I found on the Internet were somehow confusing and not helpful at all. Therefore I decided to write my own Dummies Guide to GWT and OpenID.

Dummies Guide to GWT and OpenID

First of all, it is important to know how OpenID works (please check the OpenID site for more info).

In a nutshell, OpenID allows you to authenticate with website (supporting the standard) with just an URL and voila. Your URL has to be hosted by an OpenID provider in order for it to work. For example, my blog is hosted by Google on blogspot.com. Google supports OpenID authentication therefore if a reader wanted to leave a comment on my blog, he does not have to have a Google Account as he can log-in with his Yahoo or AOL or Facebook or WordPress or any other OpenID provider sites, and then leave a comment, that simple.

GWT to OpenID and back

There are two ways to authenticate a user with an OpenID provider and GWT supports both. When authenticating a user, the relaying site (the site the user is trying to access) redirects to user to the OpenID provider (i.e. Google) login page.

The problem will be with the GWT RPC mechanism. GWT RPC calls are asynchronous and you cannot make any redirections. Therefore we need a way to execute the redirection from the client side, here is the code (I use OpenID for Java to handle the openID discovery from the RPC servlet), I then used USER object (just a simple POJO which only stores the redirection URL and the parameters) to be sent back and forth between the front-end and back-end.

#######################################################
public User authenticateOpenId(String provider_url) {
    try {
        ConsumerManager manager = new ConsumerManager();
        // This is the URL where the OpenID provider will redirect the user
        // once logged in.
        String returnToUrl = “http://localhost:8084/GwtOpenId“;
       
        // the provider URL will be used to identify the user OpenID provider
        List discoveries = manager.discover(provider_url);
        DiscoveryInformation discovered = manager.associate(discoveries);
        // OpenID 4 Java needs to  have an HttpServletRequest object, GWT sevlet 
have
        // convenient methods to retrieve the HttpServletRequest object 
and manipulate its
        // parameters
        this.getThreadLocalRequest().setAttribute(“openid-disc”, discovered);
        this.getThreadLocalRequest().setAttribute(“openid.mode”, “popup”);
       
        AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
        FetchRequest fetch = FetchRequest.createFetchRequest();
        // I want to exchange the following attributes from the OpenID provider
        // remember that teh attribute will be returned only if it exits
        fetch.addAttribute(“email”,”http://schema.openid.net/contact/email“,true);
        authReq.addExtension(fetch);
        // Simple POJO to persist the data
        User user = new User();
        // In a normal servlet development, the following statement would make
        // a redirect call but this would not work when using GWT RPC
        if(!discovered.isVersion2()){
            user.setRedirect(authReq.getDestinationUrl(true));
            // fakes the redirect by sending the POJO with the required parameters
            // to make a client-side redirect
            return user;
            } else{
            user.setParams(authReq.getParameterMap());
            user.setRedirect(authReq.getDestinationUrl(false));
            // fakes the redirect by sending the POJO with the required parameters
            // to make a client-side redirect
            return user;
        }
        } catch (MessageException ex) {
        Logger.getLogger(GWTServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        return null;
        } catch (DiscoveryException ex) {
        Logger.getLogger(GWTServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        return null;
        } catch (ConsumerException ex) {
        Logger.getLogger(GWTServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
#############################################################

The above codes will format the request in order for the front-end to execute a redirect and allow the user to authenticate with his OpenID provider. Now here is the front-end code which executes the authentication and reads the data back.

#################################################################
// This is an extract from the openidEntryPoint.java

// This is where the magic happens – This code is only usefull when the OpenID 
provider
// redirects the user back to your site – please visit openid.net for valid 
parameters.
// The “if” statement checks to make sure that it is a valid response from 
the OpenID
// provider – You can do anything you want with the results here such 
as verifying the
// response with the server-side code
if(Window.Location.getParameter(“openid.rpnonce”) != null){
    String s = Window.Location.getParameter(“openid.mode”);
    // executes this if the user cancels the authentication process and the OpenID
    // providers returns to the your site
    if(s.equals(“cancel”)){
        sign.setText(“Server returned openid.mode=cancel”);
        openIdUrl.setText(“You need to Accept not Cancel”);
    }
    // Here, I am assuming that everything is fine and that the user has 
been sucessfully logged in
    else{
        sign.setText(“You have successfully signed in”);
        vp.setVisible(false);
    }
   
}
RootPanel.get().add(contentPanel);

}

private class UserAsyncCallback implements AsyncCallback<User> {
   
    public void onFailure(Throwable caught) {
        Window.alert(caught.getLocalizedMessage());
    }
   
    public void onSuccess(User result) {
        if (result != null) {
            //                    Window.open(result.getRedirect(), “_blank”,
 “height=200,width=400,left=100,” +
            //                            “top=100,resizable=no,scrollbars=no,
toolbar=no,status=yes”);
            // this the most important line in order to make the authentication.
 Here, I am redirecting the user
            // from the client side to the OpenID provider URL with the discovery
 data generated from the
            // RPC call to the servlet.
            Window.Location.assign(result.getRedirect());
            } else {
            Window.alert(“Ooops!!! Couldn’t find your provider”);
        }
    }
}
#######################################################################################################

I have attached the full NetBeans project with dependencies. The code is provided as-is and use at your own risk ;). Here is a screenshot of the working application:

Step1: Authenticate on the site (enter the URL)
moz-screenshot-6

Step2: Redirect to OpenID provider (Google is my provider 🙂 ), authenticate with your provider
moz-screenshot-7

Step3: Allow the application to access your OpenID details and redirect back to the original site
moz-screenshot-8

Step4: final step, check the parameters from the provider and proceeds accordingly
moz-screenshot-9

Take a look at the URL in each of the above step to see the OpenID data. OK, so my code actually works (yuppie), now you know that it is possible form GWT to OpenID and it’s not as complicated as many other sites are trying to show. The code is just for authentication but once authenticated, you can retrieve any parameters that you need. In this example, the query is sent through the browser URL (GET) but you can change it to be encoded in a form submit action. Iwrote some of the code to allow the user to authenticate via a popup window, the code is not complete and maybe someone else might want to have a go. My only problem is getting the redirect back to the original window but apart from that it works.

Download the source code

I hope you guys enjoyed it and Happy Coding.

pixy

JavaFX vs GWT – A developer dilemma in building a RIA application

For the past few days, I have been working on a simple proof of concept; a web based stock streaming application with a community theme to it. I set myself to building the backend first. As you can guess, I am developing in Java and here are some of the requirements that I have to meet, at least:

  1. The application shall allow the user to query a stock (quotes) either using the stock ticker or the company name and display the following: stream stock price with basic info, stock historical price; tabular view and financial chart analysis.
  2. The ability to rate, comments and share stock information.
  3. provide a real-time chat features for users of the application to interact together.
  4. single sign-on integration with OpenSocial, OpenID and Facebook connect.

The above are some basic features in order for people to actually use the site. As you can see, they are mostly front-end requirements. Here is another important requirement:

  • The application will be hosted on a Cloud-based service, the application shall keep to a minimum the load on the server as CPU and memory use will be charged per request.

I believe that last requirement was the key decision factor. I needed something that will make use of the user resources instead of stressing the server. Something that would execute on the browser, client-side. Being a Java developer, it is only normal for me to look for something that I can grasp easily and freely available on the market. I looked at a few RIA frameworks and tools but I needed something that can integrate within my development environment without the need switch between IDEs.

I had a look at JavaFX and GWT. Having worked on GWT in the past, I found that I could implement most of the requirements. GWT has a rich api and components sets (widgets). I could use the Google search, map, visualization… to build the front-end and implement the client side code.

It took me about two days to implement the basic front-end and back-end features; mostly concentrating requirements 1 and the last. But then I hit a brick wall, something that all Javascript developers already knew but I just came across:

The application is a mashup of different services from around the net. Some of those services were available for free and others were not available at all but I will still be connecting and parsing the relevant data to displayed on the screen. As requirement “1” was working fine, there was a disaster about to happen. Here is the basic architecture:

  • when a user queries a stock, the data is sent to the back-end services.
  • the back-end services queries a third-party web service which I do not have control over. ZERO.
  • when the third-party web service returns, the data is then parsed into a format understood by the front-end and sent to the front-end services to display. 

The services was working fine until I had about 12 stocks displayed on my screen for testing purpose. The data was being streamed with a 1 minute interval. After about 30minutes later (and 360 requests = 12 *1 pm * 36m), I have noticed that the stock data was not being updated anymore and some screens were blank. No errors were logged and some other queries were still working such as the historical data. As I could not see the errrors from my debugging session, I therefore decided to query the third-party service manually through Firefox and IE and VOILA! The service provider had put a temporary ban on my IP address for making too many requests, it says. This was a major blocker as it seems that I could not access my primary data anymore. This left me questioning the feasibility of the project.

If a single user gets banned for tracking 12 stocks, what would happen when 100 or more users start watching their stocks?

OK, so I did not give up, at least not without a fight!

I looked at the problem from another perspective, the third-party view. How do they track my request as I do not have to register or sign-in? The obvious answer is my IP. So I thought, instead of making the request to their services from the back-end, I should send the request directly from the front-end. If each users make the same request, the third-party services would register different IP addresses for each one of them. Correct indeed but one big problem:

The front-end code is written in GWT which is then compiled to Javascript. Being a Java developer, I was not aware of the limitation of using AJAX in a mashup such as mine. After making the necessary changes, I then run the app just to get hit with another blocker – SOP (Javascript Same Origin Policy). What’s in a monkey name was this all about? So after researching it – Google and Wikipedia, I knew what I was dealing with and I am sure all Javascript developers already knew that but not me :(. I never give up, it is not part of my nature, therefore I decided to look for ways around it and came across a tutorial on GWT site that shows you how to implement a workaround. Did the tutorial, implemented some basic methods and that worked fine but implementing the third-party service, did not work :(. The problem was simple, the workaround needs to be in JSON format which I coded but the third-party service needs to be able to send the request back to a “callback” method. This is it!!! Remember that I mentioned that I had ZERO control over the thrid-party service and therefore I could not implement this feature.

Remember, I never give up; when there’s a will there’s a way. So I hit a major blocker due to the technology, in this case it was Javascript. I know that if I was working on a pure java front-end GUI, this would have never occurred and Flex allows you to query other third-party services but I have no knowledge of ActionScript. I decided to go for JavaFX just because it is Java and allows me to connect and get my data (actually it’s not mine). My options were Webstart, Applet and JavaFX. First of all, it has to be part of the site so my real options were Applet and JavaFX. Applet do not have a rich set of tools such as Map, Chart and everything else that JavaFX provides and I do not want to waste time coding them.

So same adventure but different episode; I am currently looking to implement the JavaFX UI so stay tune for the sequel and screenshot. I could have never anticipated those problems with the third-party and then Javascript but believe me it was a good experience and my Javascript just went +1.