Cross-site request forgery (CSRF)

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

Description

CSRF tricks a browser into sending a request the victim did not intend when it automatically supplies credentials such as cookies. Without checking the request's legitimacy, the server may perform an action with the victim's permissions.

Potential impact

  • Account settings or data may be changed with the victim's permissions.
  • Exposed sensitive operations may allow service interruption or abuse of privileges.
  • Changes to disclosure or forwarding settings may expose data. CSRF itself does not let an attacker read the response body.

Remediation

  • Use the framework's CSRF protection, or issue an unpredictable session-bound token and validate it before state changes.
  • Apply the SameSite cookie attribute as an additional defense; do not assume it replaces token validation.
  • Review CORS and request-origin validation, and add checks such as reauthentication for sensitive actions.

Examples

These are controller-method excerpts. Check whether another filter already validates CSRF. The after-example assumes that the server has issued an unpredictable csrf_token and safely supplied it to the session and 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: This method has no CSRF check. Cookie-authenticated requests may be abused if no other layer protects them.
  • After: Compares the submitted token with the session token before performing the action. User authentication and operation-specific authorization remain necessary.

Related CVEs

References