Question

I have a login screen and i want to authenticate users by checking credentials from database. I know most browsers can remember the password, but how can i implement Remember me check box by using the browser cookies? I am using sign.jsp and Auth servlet (doPost) and basic access authentication with https.

I know I need to store the userid + token into cookies. I found the following codes from another thread.

In your servlet response handler (doPost, doGet etc.) create a cookie in the following way -

if(remember_me_is_checked)
{
    Cookie c = new Cookie("userid", userId.toString());
    c.setMaxAge(24*60*60);
    response.addCookie(c);  // response is an instance of type HttpServletReponse
}

To read them, you can use something like this -

Cookie[] cookies = request.getCookies();     // request is an instance of type 
                                             //HttpServletRequest
boolean foundCookie = false;

for(int i = 0; i < cookies.length; i++)
{ 
    Cookie c = cookies[i];
    if (c.getName().equals("userid"))
    {
        string userId= c.getValue();
        foundCookie = true;
    }
} 

My question is, after I store user info into cookies, how can I sign the user in automatically when the user logs in next time? What I dont understand is that I only have user's login id stored in cookies, how could I sign the user in without password. What method could I use?

Please explain or provide some codes specifically if possible. I am really new to this kind of stuff.

Best Regards

Was it helpful?

Solution

Generally we store token - a status information to determine whether as user is logged or not, into the cookies. (Do not store password and other credential in cookies).

I'd like to suggest you to use filter. In doFilter() method read cookies and based upon cookie's value or availability of cookie you may authenticate a request.

OTHER TIPS

It's not enough to store only userid in the cookie. The simplest solution I see is to store some sort of password hash along with the userid.

Take userid + some_secret_string + password.

Calculate the hash function out of it.

Push the userid and computed hash to the cookie.

When the user returns you'll get 2 strings.

Based on the userid you'll get the password from your database.

Calculate the hash function again.

Compare the calculated hash with the one from the cookie.

If they match - user is logged in again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top