How to check whether a user is logged in or not in Servlets?

authentication, jakarta-ee, java, servlets

Solution

The `HttpServletRequest#getUserPrincipal()` as pointed out in the other answer only applies when you make use of Java EE provided container managed security as outlined here.

If you're however homegrowing your own security, then you need to rely on the `HttpSession`. It's not that hard, here is an overview what you need to implement on each step:

On login, get the `User` from the DB and store it in session in servlet's `doPost()`:

User user = userDAO.find(username, password);
if (user != null) {
    session.setAttribute("user", user);
} else {
    // Show error like "Login failed, unknown user, try again.".
}

On logout, just invalidate the session in servlet's `doPost()`. It will destroy the session and clear out all attributes.

session.invalidate();

To check if an `User` is logged in or not, create a filter which is mapped with an `url-pattern` which covers the restricted pages, e.g. `/secured/*`, `/protected/*`, etcetera and implement `doFilter()` like below:

if (session.getAttribute("user") == null) {
    response.sendRedirect(request.getContectPath() + "/login"); // Not logged in, redirect to login page.
} else {
    chain.doFilter(request, response); // Logged in, just continue chain.
}

That's basically all.

See also:

- How to redirect to Login page when Session is expired in Java web application?

- How to handle authentication/authorization with users in a database?

Problem

In a Java Servlet I want to check programmatically whether a user is logged in or not.

Original source

Related problems