Popular Searches
Popular Course Categories
Popular Courses

Managing User Sessions and Access Control

Managing User Sessions and Access Control

Web Application Authentication and Security

Managing User Sessions and Access Control in Java Web Applications

Course: Advanced Java Training

Topic: Managing User Sessions and Access Control

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to User Sessions and Access Control

In Java web applications, managing user sessions and access control is essential for maintaining user identity, preserving information across requests, and protecting sensitive pages and operations. HTTP is stateless, which means that each request is independent by default. A web application therefore needs a mechanism to recognize a user across multiple requests.

Session management maintains information associated with a user during a visit, such as authentication status or a temporary shopping cart. Access control determines which resources and operations that user is permitted to access.

For example, an online learning platform may allow visitors to view courses, registered learners to access lessons, and administrators to manage course content. Sessions help identify the signed-in user, while access-control rules enforce the permissions associated with that user.

2. Learning Objectives

  • Understand HTTP statelessness and the purpose of sessions.
  • Learn how to create, access, update, and invalidate an HttpSession.
  • Understand cookies, session identifiers, and session expiration.
  • Differentiate authentication from authorization.
  • Implement role-based access control in Java web applications.
  • Protect servlets and application resources from unauthorized access.
  • Apply secure session-management practices and test common security scenarios.

3. What Is a User Session?

A user session is a temporary association between a client and a web application that allows the application to retain selected information across multiple HTTP requests. In Java Servlet applications, the HttpSession interface is commonly used for this purpose.

Example Scenario

When a user signs in to an application, the server validates the submitted credentials. If the credentials are valid, the application creates or updates a session and stores the authenticated user's identifier. On later requests, the application checks the session to determine whether the user is signed in.

Common Session Data

  • User ID or username.
  • Authentication status.
  • Shopping cart or temporary workflow data.
  • Selected language or interface preferences.
  • Limited application-specific state needed across requests.

Do not store plaintext passwords, unnecessary personal information, payment-card details, or other highly sensitive data in session attributes. Keep session data minimal and protect the session identifier.

4. Understanding HTTP Statelessness

HTTP does not automatically remember previous requests. If a browser sends one request to a servlet and then sends another, the server needs a way to associate the requests with the same session.

Concept Description
HTTP request A message sent by a client to a server to request a resource or operation.
HTTP response The server's reply, containing a status code, headers, and sometimes a response body.
Session Server-side state associated with a client over multiple requests.
Session ID An identifier used to associate a request with a session.
Cookie A browser-stored value that can be sent with later requests to the same eligible site.

5. The HttpSession Interface

HttpSession belongs to the Java Servlet API and provides methods for storing and retrieving session attributes, checking session metadata, and invalidating a session.

Important HttpSession Methods

Method Purpose
request.getSession() Returns the current session or creates one if necessary.
request.getSession(false) Returns the existing session or null if no session exists.
session.setAttribute(name, value) Stores an object as a session attribute.
session.getAttribute(name) Retrieves a session attribute.
session.removeAttribute(name) Removes one session attribute.
session.invalidate() Invalidates the session and its attributes.
session.getId() Returns the session identifier.
session.setMaxInactiveInterval(seconds) Sets the inactivity timeout in seconds.
session.getMaxInactiveInterval() Returns the configured inactivity timeout in seconds.

6. Creating and Managing a Session

The following servlet example creates a session and stores the user's display name. In a real application, the value should come from a trusted authentication process rather than from an unverified form field.

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/start-session")
public class StartSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        session.setAttribute("displayName", "Aarav");
        session.setMaxInactiveInterval(15 * 60);

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Session created successfully.");
    }
}

This example uses the Jakarta Servlet namespace (jakarta.servlet), which is used by modern Jakarta EE servlet environments. Older Java EE applications may use javax.servlet; use the namespace that matches the project's server and dependencies.

Important Points

  • Calling getSession() may create a new session.
  • Calling getSession(false) is useful when checking whether a session already exists without creating one.
  • Session attributes can hold Java objects, so use clear, consistent attribute names.
  • Configure timeouts according to the sensitivity and needs of the application.

7. Retrieving Session Information

A servlet can retrieve data stored in an existing session. For protected pages, avoid creating a new session merely to check authentication.

HttpSession session = request.getSession(false);

if (session == null ||
    session.getAttribute("userId") == null) {
    response.sendRedirect(
        request.getContextPath() + "/login.jsp");
    return;
}

Object userId = session.getAttribute("userId");
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Authenticated user ID: " + userId);

This check is a basic authentication-state check. The application must still verify whether the user is authorized to access the requested resource or perform the requested operation.

8. Cookies and Session Identifiers

A session identifier allows the server to associate incoming requests with a server-side session. In many servlet applications, the identifier is sent to the browser in a cookie, commonly named JSESSIONID. The exact mechanism depends on the application server and configuration.

The cookie normally contains an identifier rather than all the session data itself. The server uses that identifier to locate the corresponding session.

Security Attributes for Session Cookies

Attribute Purpose
Secure Restricts the browser from sending the cookie over unencrypted HTTP connections.
HttpOnly Prevents ordinary client-side JavaScript from reading the cookie.
SameSite Controls cross-site cookie sending behavior and can help reduce certain CSRF risks.
Path and Domain Control where the browser sends the cookie.

Configure cookie attributes using the servlet container or framework's supported session-cookie configuration. Use HTTPS throughout authenticated workflows. Cookie attributes are important defenses, but they do not replace CSRF protection, output encoding, or proper authorization checks.

9. Session Timeout and Expiration

A session should not remain active indefinitely when it is no longer being used. An inactivity timeout allows the application server to expire sessions after a configured period without requests.

Setting a Timeout in a Servlet

HttpSession session = request.getSession();
session.setMaxInactiveInterval(900); // 15 minutes

Configuring a Default Timeout in web.xml

<session-config>
    <session-timeout>15</session-timeout>
</session-config>

The timeout in web.xml is expressed in minutes, while setMaxInactiveInterval() uses seconds. Actual expiration may be affected by container behavior and configuration.

Recommended Practices

  • Choose an inactivity timeout appropriate for the sensitivity of the application.
  • Use shorter timeouts for highly sensitive administrative or financial workflows where appropriate.
  • Require reauthentication for particularly sensitive actions when necessary.
  • Explain session expiration clearly and provide a safe sign-in flow.
  • Do not treat an inactivity timeout as a substitute for explicit logout.

10. Logging Out and Invalidating a Session

Logging out should invalidate the authenticated session so that its attributes cannot continue to be used. The application should also clear any related authentication state managed by its framework or identity provider.

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws IOException {

        HttpSession session = request.getSession(false);

        if (session != null) {
            session.invalidate();
        }

        response.sendRedirect(
            request.getContextPath() + "/login.jsp");
    }
}

Logout is implemented as a POST request here because it changes authentication state. Protect the logout form with appropriate CSRF defenses, particularly when using cookie-based authentication.

Logout Checklist

  • Invalidate the server-side session.
  • Clear relevant authentication state and security context.
  • Use CSRF protection for state-changing logout requests where applicable.
  • Redirect the user to an appropriate public page.
  • Prevent sensitive cached pages from being exposed after logout where necessary.

11. What Is Access Control?

Access control is the process of determining whether a user, role, or other identity is allowed to access a resource or perform an operation. It helps prevent users from viewing private information or changing data beyond their permissions.

Examples include restricting the administration dashboard to administrators, allowing signed-in learners to access enrolled courses, and permitting users to edit only their own profiles.

Core Access-Control Concepts

  • Subject: The user or identity requesting access.
  • Resource: The page, data, API endpoint, or operation being protected.
  • Permission: The action allowed on a resource, such as read, create, update, or delete.
  • Role: A named collection of permissions, such as ADMIN, INSTRUCTOR, or STUDENT.
  • Policy: The rules used to decide whether a request is permitted.

12. Authentication vs. Authorization

Authentication Authorization
Verifies who the user is. Determines what the user may access.
Usually happens during sign-in or identity verification. Happens whenever a protected resource or operation is requested.
May use a password, passkey, multifactor authentication, or an external identity provider. May use roles, permissions, ownership rules, or policy checks.
Example: validating a user's login credentials. Example: checking whether the signed-in user may delete a course.

A user can be authenticated but still lack permission to access a particular resource. Always perform authorization checks independently of authentication.

13. Role-Based Access Control (RBAC)

Role-Based Access Control assigns permissions to roles and then associates users with those roles. This approach makes it easier to manage permissions across an application.

Role Example Permissions
ADMIN Manage users, courses, and application settings.
INSTRUCTOR Create and update assigned course content.
STUDENT View enrolled courses and manage permitted profile details.
GUEST View public course information.

Roles should be assigned by a trusted administrative or identity-management process. Never allow users to grant themselves privileged roles by submitting a form field or changing a request parameter.

14. Implementing Basic Role Checks in a Servlet

The following example illustrates a simple role check. It assumes the user's role was established by a trusted authentication process and stored in the session. Production applications should generally prefer the security features of their framework or servlet container over scattered custom checks.

import java.io.IOException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/admin/dashboard")
public class AdminDashboardServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws IOException {

        HttpSession session = request.getSession(false);

        if (session == null ||
            session.getAttribute("userId") == null) {
            response.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "Authentication required");
            return;
        }

        String role = (String) session.getAttribute("role");

        if (!"ADMIN".equals(role)) {
            response.sendError(
                HttpServletResponse.SC_FORBIDDEN,
                "You do not have permission to access this page");
            return;
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Welcome to the admin dashboard.");
    }
}

Important: This sample demonstrates the decision flow, not a complete production security system. In a real application, ensure that session identity and role data are created only by trusted server-side authentication logic, and enforce permissions for every protected operation.

15. HTTP Status Codes for Access Control

Status Code Meaning Typical Use
200 OK The request succeeded. An authorized request was processed successfully.
302 Found Redirect response. Redirecting a browser to a sign-in page.
401 Unauthorized Authentication is required or invalid. An API request lacks valid authentication.
403 Forbidden The server refuses the requested operation. An authenticated user lacks the required permission.
404 Not Found The resource was not found or is intentionally concealed. Returning a not-found response where revealing resource existence is undesirable.

For browser-based applications, redirecting unauthenticated users to a login page may be appropriate. For APIs, use consistent HTTP status codes and error formats. The correct response depends on the application's security design.

16. Protecting Pages with Servlet Filters

A servlet filter can intercept requests before they reach a servlet. Filters are useful for cross-cutting tasks such as request logging, security headers, and authentication checks. Authorization should be enforced consistently, and a filter must not become the only protection if some endpoints bypass it.

Example Authentication Filter

import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebFilter("/protected/*")
public class AuthenticationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest =
            (HttpServletRequest) request;
        HttpServletResponse httpResponse =
            (HttpServletResponse) response;

        HttpSession session = httpRequest.getSession(false);

        if (session == null ||
            session.getAttribute("userId") == null) {
            httpResponse.sendRedirect(
                httpRequest.getContextPath() + "/login.jsp");
            return;
        }

        chain.doFilter(request, response);
    }
}

The @WebFilter("/protected/*") mapping applies this filter to matching URLs. The filter checks for an authenticated session before allowing the request to continue. It does not check whether the user has the specific role or permission needed for every operation, so authorization checks are still required.

17. Session Fixation and Session ID Rotation

Session fixation is an attack in which an attacker attempts to make a victim use a session identifier known to the attacker. If the application authenticates the user without changing that identifier, the attacker may be able to reuse it.

After successful authentication, rotate the session ID using the servlet container's supported mechanism. In Servlet 3.1 and later, request.changeSessionId() can change the current session identifier without discarding its attributes.

// Call only after the credentials have been
// successfully validated.
HttpSession session = request.getSession();
request.changeSessionId();

session.setAttribute("userId", authenticatedUser.getId());
session.setAttribute("role", authenticatedUser.getRole());

In production code, ensure that the session and authentication flow are handled consistently by the chosen security framework. Session ID rotation helps prevent fixation but does not replace HTTPS, secure cookies, or proper authorization.

18. Preventing Session Hijacking

Session hijacking occurs when an unauthorized person obtains and reuses a valid session identifier. Since possession of the identifier may allow access as the associated user, it must be protected like a credential.

Prevention Techniques

  • Use HTTPS across the entire authenticated application.
  • Configure session cookies with Secure, HttpOnly, and an appropriate SameSite policy.
  • Rotate session identifiers after authentication and privilege changes where appropriate.
  • Invalidate sessions during logout and after security-sensitive events.
  • Set reasonable inactivity timeouts.
  • Never expose session IDs in URLs, logs, screenshots, or analytics data.
  • Use appropriate protection against cross-site scripting (XSS) and cross-site request forgery (CSRF).
  • Consider reauthentication for high-risk operations.

19. Securing Sensitive Operations

Not every signed-in user should be able to perform every operation. Sensitive actions, such as deleting a user account, changing permissions, or viewing private records, should have explicit authorization checks.

Example: Checking Resource Ownership

HttpSession session = request.getSession(false);

if (session == null ||
    session.getAttribute("userId") == null) {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return;
}

Long currentUserId =
    (Long) session.getAttribute("userId");

long requestedProfileId =
    Long.parseLong(request.getParameter("profileId"));

if (!currentUserId.equals(requestedProfileId)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return;
}

// Continue only after the ownership check succeeds.

This illustrates an ownership check for a simplified example. Production code must validate input safely, handle malformed identifiers, and enforce the ownership rule at the service or data-access boundary as appropriate. For administrative access, verify the required permission rather than relying on ownership alone.

20. Using Container-Managed Security

Java web applications can use servlet-container security features instead of implementing every authentication and authorization check manually. Depending on the application, these features may include security constraints, authenticated principals, declared roles, and programmatic checks such as request.isUserInRole("ADMIN").

Example web.xml Security Constraint

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Admin Area</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>ADMIN</role-name>
    </auth-constraint>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

<security-role>
    <role-name>ADMIN</role-name>
</security-role>

This configuration declares that the matching admin resources require the ADMIN role and a protected transport. The application server must also be configured with an authentication mechanism and a mapping between authenticated users and application roles. Exact configuration requirements vary by container and application version.

21. Common Session and Access-Control Problems

Problem Possible Cause Recommended Solution
User is logged out on every request. Session cookie is not being returned or session tracking is misconfigured. Inspect browser cookies, domain, path, HTTPS settings, and server logs.
Protected page opens without login. Authentication checks are missing or a URL is not covered by the filter or security constraint. Audit every protected endpoint and enforce authentication centrally.
Student can open admin features. Role or permission checks are missing or trust client-provided role data. Load trusted identity and permissions server-side and check them on every protected operation.
Session remains active after logout. Logout does not invalidate the server session or clear framework authentication state. Use the framework's logout mechanism and invalidate associated state.
Users lose session data after deployment. Sessions are stored in memory or deployment changes invalidate them. Review deployment behavior and consider an appropriate shared session strategy if required.
Requests fail after session timeout. The session expired while the user was inactive. Handle expiration gracefully and direct the user to authenticate again.
Access is denied to a valid user. The user lacks a required role or the role mapping is incorrect. Review role assignments and security configuration.

22. Best Practices for Session Management and Access Control

  • Use established security frameworks: Prefer a well-maintained framework or container-managed security where practical.
  • Apply least privilege: Give users only the permissions needed for their responsibilities.
  • Validate every protected request: Do not assume that hiding a link in the interface protects its endpoint.
  • Use secure transport: Protect login and authenticated requests with HTTPS.
  • Protect session cookies: Configure appropriate cookie attributes and avoid placing session IDs in URLs.
  • Rotate session identifiers: Change the session ID after successful authentication and relevant privilege changes.
  • Keep session data minimal: Store only the state required to support the user experience.
  • Invalidate sessions properly: Handle logout, expiration, and account-security events consistently.
  • Enforce ownership and tenant boundaries: Check that users can access only the records they are entitled to see.
  • Protect state-changing requests: Use CSRF defenses for cookie-authenticated operations.
  • Log security events carefully: Record useful events without logging passwords, session IDs, or other secrets.
  • Test negative cases: Confirm that anonymous users and users with insufficient privileges are denied access.

23. Practical Exercise

Project: Build a secure session-based learning portal.

Requirements

  1. Create a login page with username and password fields.
  2. Validate credentials against a trusted user store.
  3. Create an authenticated session after successful login.
  4. Rotate the session identifier after authentication.
  5. Store the authenticated user's ID and trusted role in the session or security context.
  6. Restrict the student dashboard to authenticated users.
  7. Restrict the admin dashboard to users with the ADMIN role.
  8. Allow students to access only their own permitted profile data.
  9. Implement a POST-based logout flow with appropriate CSRF protection.
  10. Configure an inactivity timeout and secure session cookies.

Testing Checklist

  • Try opening a protected page without logging in.
  • Sign in as a student and attempt to open the admin dashboard.
  • Sign in as an administrator and verify the permitted admin operations.
  • Try changing a profile ID in the URL or request body.
  • Log out and try to reuse the old session.
  • Wait for session expiration and confirm that protected access is denied.
  • Verify cookie security settings in the browser's developer tools.

24. Interview Questions and Answers

Q1. What is session management?

Session management maintains selected user-related state across multiple HTTP requests, commonly using the Java Servlet API's HttpSession.

Q2. Why is HttpSession used?

It allows a web application to store and retrieve server-side attributes associated with a user's session, such as the authenticated user ID.

Q3. What is the difference between getSession() and getSession(false)?

getSession() returns the current session or creates one. getSession(false) returns the current session if it exists and otherwise returns null.

Q4. What does session.invalidate() do?

It invalidates the session and unbinds the attributes associated with it. The application should also clear related authentication state managed elsewhere.

Q5. What is the difference between authentication and authorization?

Authentication verifies a user's identity, while authorization determines which resources or operations the user may access.

Q6. What is role-based access control?

RBAC assigns permissions to roles and associates users with those roles, allowing access decisions to be based on trusted role assignments.

Q7. What is session fixation?

Session fixation is an attack in which an attacker attempts to make a victim use a known session identifier. Rotating the identifier after authentication helps mitigate this risk.

Q8. Why are Secure and HttpOnly cookie attributes important?

Secure restricts cookie transmission to secure connections, while HttpOnly prevents ordinary JavaScript from reading the cookie. Both reduce certain risks but do not eliminate every session attack.

Q9. Why should authorization be checked on the server?

Client-side controls can be bypassed. The server must verify permissions for each protected resource and operation.

Q10. What is the purpose of a servlet filter?

A filter intercepts matching requests and responses, enabling common logic such as authentication checks, logging, and security-header handling.

Q11. What is the difference between HTTP 401 and 403?

HTTP 401 indicates that valid authentication is required or has not been provided. HTTP 403 indicates that the server refuses the request, commonly because the identity lacks permission.

Q12. Why is session timeout necessary?

An inactivity timeout limits how long a session remains active without requests, reducing the exposure from unattended or abandoned sessions.

25. Quick Revision

  • HttpSession stores server-side state across requests.
  • getSession(false) checks for an existing session without creating one.
  • Session IDs should be protected as credentials.
  • Use HTTPS and secure cookie attributes.
  • Rotate the session ID after authentication.
  • Use timeouts and invalidate sessions during logout.
  • Authentication establishes identity; authorization checks permissions.
  • RBAC uses roles to organize permissions.
  • Filters and container security can help enforce consistent protection.
  • Validate resource ownership and permissions on the server for every sensitive operation.

26. Conclusion

Managing user sessions and access control is a fundamental part of building secure Java web applications. By understanding HttpSession, cookie-based session tracking, session expiration, logout, authentication, role checks, and resource ownership, developers can build applications that preserve user state without exposing protected resources.

For production applications, combine secure session practices with a maintained security framework or container-managed security, HTTPS, CSRF defenses, careful authorization checks, and regular security testing.

27. Learn More with JustAcademy

Explore the Advanced Java Training course to continue learning about Java web development, servlets, sessions, and application security.

Interested in learning more? Register for a course demo or visit the JustAcademy website for additional learning resources.

Previous Next
whatsapp