0
0
JavascriptConceptBeginner · 3 min read

What is CSRF in JavaScript: Explanation and Example

In JavaScript, CSRF (Cross-Site Request Forgery) is a security attack where unauthorized commands are sent from a user that the website trusts. It tricks the browser into sending unwanted requests, often by exploiting the user's logged-in session. Developers use tokens and checks in JavaScript to prevent these attacks.
⚙️

How It Works

Imagine you are logged into your bank website. While logged in, you visit another website that secretly sends a request to your bank to transfer money without your permission. This is what CSRF does: it tricks your browser into sending commands to a trusted site using your login details.

JavaScript can be involved in both the attack and the defense. The attacker might use JavaScript on a malicious page to send hidden requests. To stop this, websites use special secret tokens that JavaScript can check before sending requests. If the token is missing or wrong, the request is blocked.

💻

Example

This example shows how a CSRF token can be added to a request in JavaScript to protect against CSRF attacks.
javascript
const csrfToken = '123abc'; // This token is usually generated by the server

async function sendSecureRequest() {
  const response = await fetch('/api/transfer', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrfToken
    },
    body: JSON.stringify({ amount: 100, toAccount: '987654321' })
  });
  const result = await response.json();
  console.log(result.message);
}

sendSecureRequest();
Output
Transfer successful
🎯

When to Use

You should use CSRF protection whenever your JavaScript code sends requests that change data on a server, like submitting forms, making payments, or updating profiles. This is especially important for websites where users log in and have sensitive information.

Real-world use cases include online banking, shopping sites, social media platforms, and any web app that requires user authentication. Adding CSRF tokens and verifying them on the server side helps keep user data safe from unauthorized actions.

Key Points

  • CSRF tricks browsers into sending unwanted requests using a logged-in user's credentials.
  • JavaScript can add CSRF tokens to requests to prove they are legitimate.
  • Always verify CSRF tokens on the server to block fake requests.
  • CSRF protection is critical for any site with user login and sensitive actions.

Key Takeaways

CSRF is a security risk where attackers trick browsers into sending unauthorized requests.
JavaScript helps by including secret CSRF tokens in requests to prove they are safe.
Always check CSRF tokens on the server to prevent attacks.
Use CSRF protection on any site that handles user logins and sensitive data.
Without CSRF protection, attackers can perform harmful actions on behalf of users.