"how to implement “stay logged in” when user login in to the web application" Code Answer

1

java ee 8 and up

if you're on java ee 8 or newer, put @rememberme on a custom httpauthenticationmechanism along with a remembermeidentitystore.

@applicationscoped
@autoapplysession
@rememberme
public class customauthenticationmechanism implements httpauthenticationmechanism {

    @inject
    private identitystore identitystore;

    @override
    public authenticationstatus validaterequest(httpservletrequest request, httpservletresponse response, httpmessagecontext context) {
        credential credential = context.getauthparameters().getcredential();

        if (credential != null) {
            return context.notifycontaineraboutlogin(identitystore.validate(credential));
        }
        else {
            return context.donothing();
        }
    }
}
public class customidentitystore implements remembermeidentitystore {

    @inject
    private userservice userservice; // this is your own ejb.
    
    @inject
    private logintokenservice logintokenservice; // this is your own ejb.
    
    @override
    public credentialvalidationresult validate(remembermecredential credential) {
        optional<user> user = userservice.findbylogintoken(credential.gettoken());
        if (user.ispresent()) {
            return new credentialvalidationresult(new callerprincipal(user.getemail()));
        }
        else {
            return credentialvalidationresult.invalid_result;
        }
    }

    @override
    public string generatelogintoken(callerprincipal callerprincipal, set<string> groups) {
        return logintokenservice.generatelogintoken(callerprincipal.getname());
    }

    @override
    public void removelogintoken(string token) {
        logintokenservice.removelogintoken(token);
    }

}

you can find a real world example in the java ee kickoff application.


java ee 6/7

if you're on java ee 6 or 7, homegrow a long-living cookie to track the unique client and use the servlet 3.0 api provided programmatic login httpservletrequest#login() when the user is not logged-in but the cookie is present.

this is the easiest to achieve if you create another db table with a java.util.uuid value as pk and the id of the user in question as fk.

assume the following login form:

<form action="login" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="checkbox" name="remember" value="true" />
    <input type="submit" />
</form>

and the following in dopost() method of a servlet which is mapped on /login:

string username = request.getparameter("username");
string password = hash(request.getparameter("password"));
boolean remember = "true".equals(request.getparameter("remember"));
user user = userservice.find(username, password);

if (user != null) {
    request.login(user.getusername(), user.getpassword()); // password should already be the hashed variant.
    request.getsession().setattribute("user", user);

    if (remember) {
        string uuid = uuid.randomuuid().tostring();
        remembermeservice.save(uuid, user);
        addcookie(response, cookie_name, uuid, cookie_age);
    } else {
        remembermeservice.delete(user);
        removecookie(response, cookie_name);
    }
}

(the cookie_name should be the unique cookie name, e.g. "remember" and the cookie_age should be the age in seconds, e.g. 2592000 for 30 days)

here's how the dofilter() method of a filter which is mapped on restricted pages could look like:

httpservletrequest request = (httpservletrequest) req;
httpservletresponse response = (httpservletresponse) res;
user user = request.getsession().getattribute("user");

if (user == null) {
    string uuid = getcookievalue(request, cookie_name);

    if (uuid != null) {
        user = remembermeservice.find(uuid);

        if (user != null) {
            request.login(user.getusername(), user.getpassword());
            request.getsession().setattribute("user", user); // login.
            addcookie(response, cookie_name, uuid, cookie_age); // extends age.
        } else {
            removecookie(response, cookie_name);
        }
    }
}

if (user == null) {
    response.sendredirect("login");
} else {
    chain.dofilter(req, res);
}

in combination with those cookie helper methods (too bad they are missing in servlet api):

public static string getcookievalue(httpservletrequest request, string name) {
    cookie[] cookies = request.getcookies();
    if (cookies != null) {
        for (cookie cookie : cookies) {
            if (name.equals(cookie.getname())) {
                return cookie.getvalue();
            }
        }
    }
    return null;
}

public static void addcookie(httpservletresponse response, string name, string value, int maxage) {
    cookie cookie = new cookie(name, value);
    cookie.setpath("/");
    cookie.setmaxage(maxage);
    response.addcookie(cookie);
}

public static void removecookie(httpservletresponse response, string name) {
    addcookie(response, name, null, 0);
}

although the uuid is extremely hard to brute-force, you could provide the user an option to lock the "remember" option to user's ip address (request.getremoteaddr()) and store/compare it in the database as well. this makes it a tad more robust. also, having an "expiration date" stored in the database would be useful.

it's also a good practice to replace the uuid value whenever the user has changed its password.


java ee 5 or below

please, upgrade.

By tejas_kale on February 25 2022

Answers related to “how to implement “stay logged in” when user login in to the web application”

Only authorized users can answer the Search term. Please sign in first, or register a free account.