Cross-site request forgery (CSRF)

Block unwanted requests that misuse credentials automatically sent by the browser.

Description

For a controller that changes data, a session cookie identifies the signed-in user but does not show that the user intended the request. The browser can send the cookie automatically.

Potential impact

An unwanted update can change account data, interrupt service or change who receives shared information. CSRF alone does not grant access to the response body.

Remediation

Use the framework’s CSRF protection, or issue an unpredictable token bound to the user’s session and verify it before making changes. Use SameSite cookies as an additional control. Review origin checks and CORS, and consider reauthentication for sensitive operations.

Examples

Check whether a filter already protects this controller. The second method assumes the server has issued csrf_token, stored it in the session and supplied it to the form.

Before

java
@PostMapping("/update")
public String updateData(HttpServletRequest request) {
    String data = request.getParameter("data");
    // Update the data

    return "updateSuccess";
}

After

java
@PostMapping("/update")
public String updateData(@RequestParam("csrf_token") String csrfToken, HttpServletRequest request) {
    String sessionCsrfToken = (String) request.getSession().getAttribute("csrf_token");
    if (sessionCsrfToken == null || !sessionCsrfToken.equals(csrfToken)) {
        throw new SecurityException("CSRF Token mismatch");
    }

    String data = request.getParameter("data");
    // Update the data

    return "updateSuccess";
}

Explanation:

  • Before: The first method has no token check of its own. Its protection depends on the filters that run before it.
  • After: The method reads data only after the submitted csrf_token matches the session token. Apply the update only after validating the token and confirming that the signed-in user may make the change.

Related CVEs

References