Friday, February 4, 2011

J2EE Web Application - Simple Single SignOn (SSO)

To have a common account (username-password) for various applications of an umbrella and to have authentication at a place to access all of the applications without the need to enter password for each is called Single Sing-on (SSO).


Here is a simple SSO implementation of web applications using JSP (would run any java web server).
Steps as follows:
  1. Create views for login and success login.jsp & success.jsp respectively for example.
  2. Write the action (as a servlet) login.do for example to handle and authenticate the request if the credentials are valid.
  3. Set a session attribute on success of login, username for example.
    session.setAttribute("username", userName);
  4. Create a jsp isLivingSession.jsp for example, which is going to act as javascript source and is the key part of our SSO.
login.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>
</head>
<body>
<form action="login.do?c=<%=request.getParameter("c")%>">
<input name="username" type="text" />
<input name="password" type="text" />
<input type="submit" value="submit" />
</form>
</body>
</html>

login.do
.....
if(loginSuccess){
 session.setAttribute("username", userName);
 c=request.getParameter("c");
 if(c!=null && !c.trim().equals("")){

   response.sendRedirect(c);
   //user will 
be automatically redirected to the calling application or page.
  }
 else{
response.sendRedirect("success.jsp");}
}
.......

isLivingSession.jsp

<%=session.getAttribute("username")==null?"window.location.href='http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"login.jsp?c='+unescape(window.location.href);":""%>

Add the following line in all web pages or a file which is included by all pages header of the application which should use SSO. This could be used in any server or application or platform.

<script type="text/javascript" src="yoursite.com/isLivingSession.jsp?ignore=currtimeinmilliseconds"></script> 

one more thing should be noted is the web application should support javascript, so add noscript tag in all web pages.

and thats it.. go and play.