Preventing CSRF attacks in JavaScript using tokens

CSRF (Cross-Site Request Forgery) attacks are a common security vulnerability in web applications. These attacks occur when a malicious website tricks a user’s browser into making an unintended request to another website that the user is authenticated on. To mitigate this risk, web developers can implement CSRF protection by using tokens.

A CSRF token is a unique value generated by the server and included in each request made by the client. This token is typically stored in a session or a cookie. When the server receives a request, it checks if the CSRF token is present and matches the expected value. If not, the request is considered invalid and is rejected.

Here is an example of how to implement CSRF protection in JavaScript using tokens:

Generating and Storing CSRF Tokens

  1. On the server-side, generate a random CSRF token for each user session.
  2. Store this token in a secure HTTP-only cookie or session storage.
const csrfToken = generateCSRFToken(); // Function to generate a random token

// Set the token in a cookie or session storage
document.cookie = `csrfToken=${csrfToken}; secure; HttpOnly`;

Including CSRF tokens in Requests

  1. In each form, include a hidden input field to hold the CSRF token.
  2. When making AJAX requests, include the CSRF token in the request headers.
<form method="POST">
    <!-- Other form fields -->
    <input type="hidden" name="csrfToken" value="<%= csrfToken %>">
    <button type="submit">Submit</button>
</form>
const xhr = new XMLHttpRequest();
const url = "https://example.com/api/some-endpoint";
xhr.open("POST", url);
xhr.setRequestHeader("X-CSRF-Token", csrfToken);

Validating CSRF Tokens on the Server-side

  1. For each incoming request, extract the CSRF token from the request headers or request body.
  2. Compare the extracted token with the one stored in the user session or cookie.
app.post("/api/some-endpoint", (req, res) => {
    const { csrfToken } = req.headers; // or req.body.csrfToken if sent in the body

    // Compare the received token with the one stored in the session or cookie
    if (csrfToken !== req.session.csrfToken) {
        return res.status(403).send("Invalid CSRF token");
    }

    // Proceed with the request
});

By implementing CSRF protection using tokens, you can greatly reduce the risk of CSRF attacks in your web application. Remember to include the CSRF token in every request and validate it on the server-side.