Monday, September 17, 2012

How to implement "Remember Me" or "Keep Me Signed In" option for your Web Application - JAVA Example

Most of the web applications that we see these days, have the "Remember Me" option, that keeps the user signed in. If you "check" this option, and do not log-out from the application, you will automatically be signed-in without being prompted to enter the username and password.

People usually believe that it is the browser related thing and need not be written in your application code.
It is true that it is related to the browser, but at the same time your application can interact with the browser properties to retrieve the useful data.

Suppose I have a web application, where-in the log-in page, there is an option for the user to command us to keep him signed in. In the html form where you ask the user his log-in credentials, add a checkbox with id and name as "rememberMe". If the user selects it, then a non-null value will be passed with your form for that field.

Put the following code in the jsp to which you are submitting the form:

if(request.getParameter("rememberMe")!= null){
    bytes [] bytes = request.getParameter("username") + ":" + request.getParameter("password")).getBytes();
    String encodedCredentials = Base64.encode(bytes, 0, bytes.length);
    Cookie cookie=new Cookie("myCookieName", encodedCredentials);
    cookie.setMaxAge(60 * 60 * 24 * 15);
    response.addCookie(cookie);
}

Get the values of the username and password, and encode them using an encoder(in my case I used a Base64 encoder), so that the username and password are not saved as a naive string. Then I create an instance of Cookie class, and pass my cookie name and the encoded credentials (key-value mapping), which I want to save. I set the maximum validity of this cookie as 15 days (you can set it for even longer time). After this I add this cookie instance to my HTTP response. This cookie is now saved in my browser.


Now I will write the following piece of code on my home page.


try{
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getName().equals("myCookieName")) {
        if(cookie.getValue()!= "" && cookie.getValue().length() > 0){
            try{
            response.sendRedirect("your_authentication_page.jsp?cookieEnabled=" + cookie.getValue());
            }catch(Exception e){
            e.printStackTrace();
            }
        }
        }
    }
    }catch(Exception e){
     e.printStackTrace();
}

This code tries to read the name all the cookies saved in the browser. If the name matches with the one that you have given for your application, then you know that some user credentials are already saved. You pass on the value of the cookie to your authentication page. Write the following code snippet in your authentication page.

if(request.getParameter("cookieEnabled")!=null){
    boolean bAuthenticated = false;
    String credentials = request.getParameter("cookieEnabled");
    if (credentials != null) {
        String decodedCredentials = new String(Base64.decode(credentials));
        String credArray[] = decodedCredentials.split(":");
        bAuthenticated = function_to_authenticate_user(credArray[0], credArray[1]);
    }
}


You have passed encoded credentials (as your cookie value, which you have saved previously), to your authentication page. You can now decode those credentials and call your function that authenticates the user and automatically land him to your logged-in home page. Easy!

Shoot your doubts right here!