OculusCyber Logo

OculusCyber

Home

Browse Topics


Broken Access Control : Vulnerable and Fixed Code Examples

By Oculus

November 9, 2025


Bad Example (Broken Access Control)

// BAD: Anyone can access any user profile by changing the userId in the request
@WebServlet("/userProfile")
public class UserProfileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String userId = request.getParameter("userId");

        // No authentication or authorization check
        User user = UserDAO.getUserById(userId);

        response.getWriter().println("User Profile: " + user.getName());
    }
}

⚠️ What's wrong:

  • No authentication or authorization verification.
  • Attacker can change userId in the query (e.g. /userProfile?userId=1234) to access others' data.
  • Violates OWASP A01:2021 – Broken Access Control.
  • Classic Insecure Direct Object Reference (IDOR) vulnerability.

Good Example (Fixed Access Control)

// GOOD: Enforces authorization before accessing any resource
@WebServlet("/userProfile")
public class UserProfileServlet extends HttpServlet {
    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, "Login required");
            return;
        }

        String requestedUserId = request.getParameter("userId");
        String loggedInUserId = (String) session.getAttribute("userId");

        // Enforce access control
        if (!loggedInUserId.equals(requestedUserId)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied");
            return;
        }

        User user = UserDAO.getUserById(requestedUserId);
        response.getWriter().println("User Profile: " + user.getName());
    }
}

✅ Why this works:

  • Verifies user session before access.
  • Confirms the requested userId matches the logged-in user.
  • Responds with 401 (Unauthorized) or 403 (Forbidden) instead of exposing data.
  • Follows Principle of Least Privilege and Secure Session Management.

Best Practices:

  • Never rely on client-side identifiers for access control.
  • Enforce server-side authorization checks.
  • Use framework security features (Spring Security, Jakarta EE Security).
  • Log unauthorized attempts and review them.
  • Apply defense in depth (role-based + object-level access checks).