I stand up for children in need. Please join me in helping this family.

Skip to content
Steven Roland

Using CSRF Tokens with AJAX in PHP

Building on the concepts discussed in this post, this article focuses on securing AJAX requests with CSRF tokens. AJAX is frequently used for asynchronous data submissions, and incorporating CSRF tokens is essential to prevent unauthorized actions.

Why Use CSRF Tokens with AJAX?

AJAX requests, like traditional form submissions, are susceptible to CSRF attacks. Implementing CSRF tokens ensures that only legitimate requests are processed, safeguarding your application from malicious activities.

Implementing CSRF Tokens in AJAX Requests

To secure AJAX requests with CSRF tokens, follow these steps:

1. Token Generation

Generate a CSRF token and store it in the session. This token will be sent with each AJAX request to verify its authenticity:

session_start();

function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

$csrfToken = generateCsrfToken();

2. Sending the Token with AJAX Requests

Include the CSRF token in the headers or data of your AJAX request. This ensures that the token is securely transmitted with each request:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    function sendAjaxRequest() {
        $.ajax({
            url: 'process_ajax.php',
            type: 'POST',
            data: {
                // Your data here
            },
            headers: {
                'X-CSRF-Token': '<?php echo $csrfToken; ?>'
            },
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });
    }
</script>

3. Validating the Token on the Server

On the server side, validate the CSRF token by comparing it with the session-stored token. If the token is valid, proceed with processing the request:

session_start();

function validateCsrfToken($receivedToken) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $receivedToken);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $receivedToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';

    if (validateCsrfToken($receivedToken)) {
        // Process the AJAX request
        echo "Request processed successfully.";
    } else {
        // Handle invalid token
        http_response_code(403);
        echo "Invalid CSRF token.";
    }
}

Advantages of Using CSRF Tokens with AJAX

  • Enhanced Security: Protects AJAX endpoints from unauthorized access and attacks.

  • Consistency: Ensures that all parts of the application, including asynchronous requests, are secured.

  • Flexibility: Works seamlessly with various frontend frameworks and libraries.

Best Practices

  • Token Management: Regularly regenerate and validate tokens to maintain security.

  • HTTPS: Always use HTTPS to protect token transmission.

  • Error Handling: Implement robust error handling to manage invalid token scenarios gracefully.

By integrating CSRF tokens into your AJAX requests, you can significantly enhance the security of your PHP applications, ensuring that all data submissions are authorized and protected against potential threats.

Support My Work

If you enjoy my content, consider supporting me through Buy Me a Coffee or GitHub Sponsors.

Buy Me A Coffee
or

More posts