Education

Cross-Site Request Forgery (CSRF) Protection for Full Stack APIs

When building full stack web applications, security is one of the most important things to keep in mind. Hackers and attackers are always trying to find ways to crack into systems and steal data. One of the common types of attacks on web applications is called Cross-Site Request Forgery, or CSRF. This kind of attack can be very dangerous if it is not handled properly.

In this blog, we will learn what CSRF is, how it works, and how to protect your full stack APIs from it. If you are studying in a developer course, this topic will help you understand how to build safer web applications. If you are part of a full stack developer course in Hyderabad, learning about CSRF protection is an important part of your backend and API development journey.

Let’s begin by understanding the basics.

What Is CSRF?

CSRF stands for Cross-Site Request Forgery. It is a type of attack where a hacker misleads a user into performing actions on a website without their permission. This attack takes advantage of the trust a website has in the user’s browser.

Here’s how it works:

  1. A user logs into a website and is authenticated.
  2. The website gives the user a session cookie to stay logged in.
  3. While the user is still logged in, they visit a different website created by the attacker.
  4. That malicious website sends a request to the original website using the user’s session cookie.
  5. The original website thinks the request is from the real user and performs the action.

This means a user could be tricked into making changes, transferring money, or deleting data — all without knowing it.

Example of a CSRF Attack

Let’s say you are logged into your bank’s website. While staying logged in, you visit another website with a hidden form that sends a request to the bank’s website like this:

<form action=”https://mybank.com/transfer” method=”POST”>

  <input type=”hidden” name=”amount” value=”1000″>

  <input type=”hidden” name=”toAccount” value=”attacker123″>

</form>

<script>

  document.forms[0].submit();

</script>

Because you are still logged in, the browser sends your session cookie along with this request. The bank thinks the request is from you and transfers the money.

This is why CSRF protection is very important in full stack applications.

How to Prevent CSRF in Full Stack APIs

There are several ways to protect your application from CSRF attacks. Let’s explore the most effective methods.

1. Use CSRF Tokens

One of the most common ways to protect against CSRF is by using CSRF tokens. A CSRF token is a random string generated by the server and added to forms or API requests. When the server accepts the request, it checks the token. If the token is missing or inaccurate, the server blocks the request.

How CSRF Tokens Work:

  1. The server sends a CSRF token to the client.
  2. The client includes the token in the next request (for example, in a hidden form field or header).
  3. The server checks if the token is valid.
  4. If the token is valid, the request continues. If not, it is blocked.

Most backend frameworks support CSRF tokens out of the box.

In Java Spring Boot:

Spring Security includes CSRF protection automatically. You just need to enable it.

@Override

protected void configure(HttpSecurity http) throws Exception {

    http

        .csrf().and()

        .authorizeRequests()

        .anyRequest().authenticated();

}

Spring Boot generates the token and checks it in each request.

If you’re learning through a developer course, understanding how Spring Security handles CSRF is very useful.

In Node.js (Express):

You can use the csurf package for CSRF protection.

const csrf = require(‘csurf’);

const csrfProtection = csrf({ cookie: true });

app.use(csrfProtection);

Then, send the token to the client and include it in future requests.

2. Use SameSite Cookies

SameSite cookies are a browser feature that helps protect against CSRF. When you set a cookie with the SameSite flag, the browser won’t send it with cross-site requests.

There are three types of SameSite settings:

  • Strict: Cookies are not delivered with any cross-site requests.
  • Lax: Cookies are sent only with safe requests like GET.
  • None: Cookies are delivered with all requests, but only if Secure is also set.

Example in Express:

res.cookie(‘sessionId’, value, {

  sameSite: ‘Strict’,

  secure: true,

  httpOnly: true

});

This is a simple way to improve security without adding tokens.

3. Use Authentication Tokens Instead of Cookies

If you use JSON Web Tokens (JWT) for authentication, and you store them in localStorage or sessionStorage instead of cookies, you are less vulnerable to CSRF attacks.

This is because CSRF relies on cookies being sent automatically with requests. If the token is stored outside cookies and added manually to headers, CSRF attacks are harder to perform.

This method is common in APIs used by frontend apps like React, Angular, or Vue.

Many students in a developer course in Hyderabad learn to build APIs that use JWT tokens for authentication.

4. Confirm Sensitive Actions with User Input

For extra security, ask users to confirm sensitive actions with a password, PIN, or code. For example:

  • Confirm before deleting an account
  • Enter password before transferring money
  • Use email or SMS verification

This adds a second layer of protection and helps prevent CSRF attacks even if one layer fails.

5. Check the Referer Header

You can check the Referer or Origin headers to make sure the request is coming from your own website.

Example in Node.js:

app.post(‘/secure-action’, (req, res) => {

  const referer = req.get(‘referer’);

  if (!referer || !referer.startsWith(‘https://yourdomain.com’)) {

    return res.status(403).send(‘Forbidden’);

  }

  // Continue with the action

});

This is not a full solution, but it can be an extra check.

Testing Your Application for CSRF

It’s important to test your app for CSRF weaknesses. Here are some tools you can use:

  • OWASP ZAP: Scans for CSRF vulnerabilities
  • Burp Suite: Helps test web application security
  • Postman: Manually test API behavior with and without CSRF tokens

Regular testing permits you catch problems early and fix them before attackers find them.

Real-World Example

Let’s say you are building a to-do list app. Users can log in and create tasks. You decide to use cookies for sessions.

An attacker builds a website that sends a POST request to your app to create a task like this:

<form action=”https://todoapp.com/tasks” method=”POST”>

  <input type=”hidden” name=”task” value=”Send money to attacker”>

</form>

<script>

  document.forms[0].submit();

</script>

If your app doesn’t have CSRF protection, the attacker’s form can create a task in the user’s account. But if you use CSRF tokens, SameSite cookies, and session checks, this request will be blocked.

This kind of scenario is often used in practice projects in a Java full stack developer course to help students understand real security risks.

Summary: CSRF Protection Checklist

Here is a quick checklist to protect your full stack APIs from CSRF:

  • Use CSRF tokens in all POST, PUT, DELETE requests
  • Enable SameSite, Secure, and HttpOnly flags on cookies
  • Use HTTPS for all connections
  • Consider using JWT tokens stored in localStorage
  • Validate the origin of each request
  • Add user confirmations for sensitive actions
  • Test your app regularly for CSRF issues

Final Thoughts

CSRF is a serious threat in full stack applications, but the good news is that it can be stopped with simple steps. By using CSRF tokens, secure cookies, and proper API design, you can protect your users and keep your app safe.

If you are studying in a developer course, learning CSRF protection will make you a better and more confident developer. And if you are part of a developer course in Hyderabad, these skills will help you build secure APIs that meet real-world standards.

Security is not just about writing code — it’s about protecting people. Every line of secure code helps build trust with your users. So take the time to understand CSRF, use the right tools, and build full stack applications that are strong, safe, and ready for the future.

Contact Us:

Name: ExcelR – Full Stack Developer Course in Hyderabad

Address: Unispace Building, 4th-floor Plot No.47 48,49, 2, Street Number 1, Patrika Nagar, Madhapur, Hyderabad, Telangana 500081

Phone: 087924 83183

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *