In this tutorial, we will discuss Cross-Site Request Forgery (CSRF), a common web application vulnerability, and discover several methods for preventing such attacks. By the end of this tutorial, you will understand what CSRF attacks are, why they are dangerous, and how to implement preventative measures in your HTML code.
CSRF attacks trick the victim into submitting a malicious request. They use the identity and privileges of the victim to perform an undesired function on their behalf. Prevention techniques include using CSRF tokens, SameSite Cookie Attribute, and validating the Referer Header.
CSRF tokens are random, unique values associated with a user's session. They are added as an additional parameter or header in requests from the client to the server.
<!-- A hidden field is added to the form with the CSRF token -->
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="YOUR_CSRF_TOKEN">
<!-- Other form fields -->
</form>
The SameSite attribute can be set to Strict
or Lax
. If set to Strict
, the browser sends the cookie only for same-site requests (requests originating from the site that set the cookie).
// Setting the SameSite attribute in JavaScript
document.cookie = "key=value; SameSite=Strict";
This method involves checking the HTTP Referer header and ensuring that the request was made from the same site.
Let's walk through some examples that employ these prevention methods.
The following is an example of a server-side JavaScript function that generates a CSRF token and inserts it into a form.
var csrf = require('csurf');
var express = require('express');
var csrfProtection = csrf({ cookie: true });
var app = express();
app.get('/form', csrfProtection, function(req, res) {
// Passing the CSRF token to the view
res.render('send', { csrfToken: req.csrfToken() });
});
Here's how you can set the SameSite attribute for cookies in an Express.js app:
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(function(req, res, next) {
// Set cookie with SameSite=Strict
res.cookie('myCookie', 'value', { sameSite: 'strict' });
next();
});
We have covered what CSRF attacks are, why they are dangerous, and several methods of preventing them, including CSRF tokens, the SameSite cookie attribute, and validating the Referer header.
Strict
.<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="YOUR_CSRF_TOKEN">
<!-- Other form fields -->
</form>
Strict
:var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(function(req, res, next) {
// Set cookie with SameSite=Strict
res.cookie('myCookie', 'value', { sameSite: 'strict' });
next();
});
To continue learning about web security, consider exploring other common web vulnerabilities like XSS (Cross-Site Scripting) and SQL injection.