Sobes.tech
Junior — Middle

Could you explain the principle of protection against CSRF attacks and how it is implemented in web applications?

sobes.tech AI

Answer from AI

CSRF (Cross-Site Request Forgery) is an attack where an attacker tricks a user into performing an unwanted action on a trusted site where the user is authenticated.

Protection against CSRF in web applications is implemented using unique tokens (CSRF tokens), which are generated by the server and included in forms or requests. When a form is submitted, the server checks that the token matches the expected one, confirming the legitimacy of the request.

Example implementation in PHP:

  1. Generating a token and storing it in the session:
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
  1. Including the token in an HTML form:
<form method="POST" action="submit.php">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
    <!-- other fields -->
    <input type="submit" value="Submit">
</form>
  1. Checking the token during request processing:
session_start();
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    die('CSRF error: invalid token');
}
// continue processing

Thus, the server rejects requests without a valid token, preventing CSRF attacks.