Step-by-Step Guide to Integrating OpenAuth into Your Java Application

Part of the OpenAuth Web Integration Series

by AOL Identity Team
September 21 2007

Download a Printable Version

No matter what kind of Web application you build, the process always seems to start in the same place: managing user accounts. Writing a file-sharing application for the Web? You begin by identifying who is uploading the file. Writing a chat application for the Web? You have to know who will use the chat session, so you can give them access. Because the Web is inherently multi-user, any application you build is going to require managing a list of users.

For Java applications, a couple of approaches to integrating with an identity management system are
  • Roll your own – You could build it yourself by creating a table of users, building the data accessors, encrypting the passwords, and all that back-end stuff. Then you have to create an interface for logging in, requesting passwords, sending e-mails, and so on. To do it right is a lot of work.
  • Use an identity provider – Intgerate  your application with an existing Identity Provider, such as AOL OpenAuth. In this case, I’ll show you how using the AOL Open Authentication API (OpenAuth).

Using an external identity provider offers a lot of advantages, not just to you, the application developer, but also to your customers. You get to start building your application right away, confident that you will be able to identify users and log them in quickly and reliably. And your customers will be able to reuse their existing screen names and passwords. Of course, that depends on the popularity of the identity provider; in the case of AOL this means leveraging the millions of people who have already registered with AOL Instant Messaging (AIM), among many other services.

Getting an Account

Getting started with the AOL OpenAuth system is remarkably easy. The first step is to get an AOL account. They are free, so this is easily done. If you have an AIM account you can also use that instead of an AOL account. The next step is to get a developer ID (devId) for your AOL account. To do this we start at the OpenAuth home page. Then click the Getting Started link toward the top of the page to continue.

Getting Started

Click the AOL Developer Site link to see a list of devIds associated with your account, if any.

DevId


Click the Create new devId link to access the devId request form.

Create new DevId


On this form enter your first and last name, your e-mail address, and then, most importantly, the URL where your customers should be redirected after a successful login. When you have this information filled in, submit the form and you should see results similar to the following:

DevID List

The Id field is the important one here. It is the ID you will use on the login page in your Web application.

Sample OpenAuth Application

This guide shows the integration of  OpenAuth API into a sample Java Web application. This sample application is packaged into a Java WAR archive and can be dropped into a servlet container, such as Tomcat, to get it running immediately with no source code changes. The source code for the application is included in the Java archive, in the WEB-INF folder.

Install and Run the application

  1. Register at http://dev.aol.com,  and obtain a developer key, as explained above.
  2. When the registering for the devId, choose the referer url of the form http://company.com/OpenAuthSample. Or, you can choose a URL path other than /OpenAuthSample, if you run the application under a different context path in the servlet container.
  3. Deploy the OpenAuthSample.war package by unpacking the archive into the servlet container's web application directory. In Tomcat, for example, install in the webapps directory.
  4. Edit the properties file, WEB-INF/classes/openauth/servlets/openauth.properties, to set the values for your application's base URL and devId.
  5. NOTE: You must set correct values in this configuration file, otherwise, the application will not run
  6. Start the servlet container.
  7. Access the home page of your application at the URL http://company.com/OpenAuthSample/home, where company.com is your hostname.
  8. Click the sign in link; you will be redirected to the AOL OpenAuth login page.
  9. After signing in at OpenAuth login page, you will be redirected back to you home page, which will display you login name
  10. You can sign out by clicking on the sign-out link.

Integration

This section explains the implementation of the sample application.  As the source code is included in the WAR archive, you modify the source and experiment with it to learn more about OpenAuth API.

The OpenAuth Page Flow

The following screen shot shows the page flow when the customer is not logged in to an AOL account.



OpenAuthFlow

In this application the "main", or  the "home" page, is accessible at the URL path /home.  When you first access this page, you will see a login hyperlink to allow you to login to the application. The links redirects you to the AOL OpenAuth login page.

After signing in by entering your user name and password at the OpenAuth login page, you are redirected to the /login url in the application.  The application verifies that you are signed in at AOL, by making a call to the GetInfo method of OpenAuth API. No page is displayed to the user at this time; the /login url is shown with a dashed line in the flow diagram to indicate that. After verification, the application  redirects the user to the /home URL, which is the main page of the application.

The home page now displays the user's login name and a link to sign out from the application and AOL OpenAuth.

Application Components

  1. The application contains 1 JSP, main.jsp, and three servlets - MainServlet, LoginHandler and LogoutHandler.
  2. The configuration properties are set in the openauth.properties file

Main.jsp

The entire JSP file is listed below.
<%@ page contentType="text/html; charset=utf-8" language="java" pageEncoding="UTF-8"%>
<%@ page session="false"%>

<%
String loginId = (String) request.getAttribute("loginid");
String logoutUrl = (String) request.getAttribute("logoutUrl");
String loginUrl = (String) request.getAttribute("loginUrl");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OpenAuth Sample Application</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>

<body>
<h1>
OpenAuth Sample Application
</h1>
<h2>
Welcome!
</h2>
<%
if (loginId == null) {
%>
To access your personalized page,
<a href="<%= loginUrl %>" title="Login">sign in</a>.
<%
} else {
%>
You are signed in as <%=loginId%>. <a href="<%=logoutUrl%>" title="Signout">Click here to sign out</a>.
<%
}
%>
</body>
</html>
  1. The JSP is not accessed directly, but, instead the servlets forward the request to this JSP.
  2. The loginid, loginurl and logouturl attributes are made accessible to the JSP by the servlets.
  3. If the loginid is available, that means the user is signed in and the JSP displays the user's login name and sign-out link.
  4. If the loginid is not available, the user is not signed-in and the JSP displays the sign-in link.

MainServlet

This servlet is mapped to the "/home" URL path. The main section of code, from the doGet method of this servlet, is listed below.

	String devId = MainServlet.getProperty("DEV_ID");
String cookieValue = getSessionCookie(request);
String sessionValue = (String) sessionStore.get(cookieValue);

if (sessionValue == null) {
// session not present, so user not signed in
// set login url in request attribute, for JSP to use in login link
String loginSuccUrl = MainServlet.getProperty("HOST_URL") + request.getContextPath() + "/login";
String loginUrl = "http://api.screenname.aol.com/auth/login?f=qs"
+ "&succUrl=" + loginSuccUrl + "&devId=" + devId;
request.setAttribute("loginUrl", loginUrl);
} else {
// session available, user is signed in
// set loginid and logout url in request attribute, for use by JSP
String[] fields = sessionValue.split(" ");
String loginId = fields[0];
String token = fields[1];
request.setAttribute("loginid", loginId);
String encodedToken = URLEncoder.encode(token, "UTF-8");
String returnUrl = MainServlet.getProperty("HOST_URL") + request.getContextPath() + "/logout";
String logoutUrl = "http://api.screenname.aol.com/auth/logout?f=qs"
+ "&succUrl=" + returnUrl
+ "&devId=" + devId
+ "&a=" + encodedToken;
request.setAttribute("loginid", loginId);
request.setAttribute("logoutUrl", logoutUrl);
}
// forward to home page
String nextJSP = "/main.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
  1. The servlet attempts the session cookie by calling  getSessionCookie, a utility method defined in this servlet..
  2. If the session cookie is not available, it means the user is not signed in.
    • the signin url, pointing to the OpenAuth login url, and containing the application's devId, is built.
    • the signin url is passed as a request attribute to the JSP main.jsp.
  3. If the session cookie is available, it means the user is signed in
    • A sign-out url, pointing to the OpenAuth logout url, and containing the applications's devId and the authentication token, is built.
    • the sign-out url also includes succUrl parameter; it's value points to the logout handler URL in the application - /logout
    • The user's login name and the logout url are sent as request attributes to the JSP main.jsp

LoginHandler

The LoginHandler executes the post-login functions.

String homePageUrl = MainServlet.getProperty("HOST_URL") + request.getContextPath()+ "/home";
String statusCode = request.getParameter("statusCode");

if ((statusCode != null) &&
(statusCode.equals("200"))) {
// retrieve and validate the token by calling OpenAuth getInfo
String token = request.getParameter("token_a");
String encodedToken = URLEncoder.encode(token, "UTF-8");
String devId = MainServlet.getProperty("DEV_ID");

String getInfoUrl = OPEN_AUTH_GET_INFO_URL + "f=qs"
+ "&devId=" + devId
+ "&referer=" + homePageUrl
+ "&a=" + encodedToken;
Map responseParamMap = getHttpResponseParameters(getInfoUrl);
statusCode = (String) responseParamMap.get("statusCode");
if ((statusCode != null) &&
(statusCode.equals("200"))) {
String loginID = (String) responseParamMap.get("userData_loginId");
// use a random number for session identifier
int sessionId = randomGenerator.nextInt();
String sessionIdStr = Integer.toString(sessionId);
// save loginid and token in session store
String sessionValue = loginID + " " + token;
MainServlet.putSession(sessionIdStr, sessionValue);
// save sessionId in cookie; in a real app, the cookie value would be encrypted
Cookie oaCookie = new Cookie("OA_SAM_C", sessionIdStr);
response.addCookie(oaCookie);
}
}
response.sendRedirect(homePageUrl);
      
  1. This servlet is mapped to the "/login" URL path  in the application.
  2. The user is redirected to this url after the user signs in at the OpenAuth server.
  3. A call is made to the OpenAuth getInfo method, to validate the token and obtain the user's login name.
    • an URL to call the OpenAuth getInfo is constructed
    • this URL includes the devId,  referer and token parameters
    • the getHttpResponseParameters method  makes a http request to the getInfo url and returns the response parameters in a Map
  4. The user's loginid is retrieved from the getInfo response.
  5. The user's login name and token are stored in the session store; a random number is used as the session identifier.
  6. The session identifier is saved in a cookie.
  7. The request is forwarded to the main page.

LogoutHandler

The LogoutHandler removes the user's session, effectively signing out the user from the application. The URL for the logout url is passed as the succUrl parameter to the OpenAuth logout method. So, this servlet is invoked by a redirect by the OpenAuth logout method.

	String statusCode = request.getParameter("statusCode");
if ((statusCode == null) ||
(!statusCode.equals("200"))) {
// error processing
} else {
// check if session cookie is present
String cookieValue = MainServlet.getSessionCookie(request);
if (cookieValue != null) {
// delete session
MainServlet.removeSession(cookieValue);
// delete cookie
Cookie sessCookie = new Cookie("OA_SAM_C", " ");
sessCookie.setMaxAge(0);
response.addCookie(sessCookie);
}
// redirect back to home page
String homePageUrl = MainServlet.getProperty("HOST_URL") + "/" + request.getContextPath()
+ "/home";
response.sendRedirect(homePageUrl);
}
  1. When a user clicks on the sign-out link on the main page, the user is redirected to the OpenAuth logout url
  2. The OpenAuth server then redirects the user to the logout url, /logout, served by the LogoutHandler servlet.
  3. The session cookie is retrieved by calling the getSessionCookie method in MainServlet.
  4. The session identifier is retrieved from the cookie.
  5. The user's session is deleted from the session store, and the cookie is deleted.
  6. The user is redirected to the home page, /home.

Going On from Here

This isn't the only service that AOL offers. AOL is opening APIs and technologies from identity to instant messaging, media and community, and providing Web application developers with a wide range of scalable solutions. In addition to the Web AIM widgets, AOL has a file-hosting service called OpenXdrive that you can use to host image or movie files, the same way developers are using Amazon's Simple Storage Service (Amazon S3) Web service. AOL has a video-sharing service similar to YouTube, and an industry-leading video search engine called Truveo. MapQuest maps can be integrated into your page. All the currently available AOL Open APIs, and associated documentation, are at http://dev.aol.com/apis. AOL is really opening up and this article shows you how easily AOL APIs can be integrated into your applications.

Conclusion

Even if you don’t want to use OpenAuth as your identity management system, this API presents an easy way to give users access to your service with minimal hassle. And if you want to use it as your user management system, you get a very easy-to-use API for free. It’s definitely worth your time to look into using OpenAuth on your site. That way you get to concentrate of the fun features that make your site interesting and avoid the hassle of reimplementing user account and password maintenance features for the umpteenth time.

Thanks a lot!

Bst Rgds,
Michael B.