What is a CSRF attack

Corss-site Request forgery (CSRF), also abbreviated as XSRF, is a common Web attack.

In simple terms, A CSRF attack is that when A user visits A normal website, he leaves some login information (such as cookies) in the browser. The malicious website B uses the login information to forge some request information and tell A normal website A that it is A legitimate user, so as to attack website A.

The following diagram illustrates the process and principle of the attack:

How do I defend against CSRF attacks

When defending against CSRF attacks in a project, you can follow the following aspects:

  • The Get request does not modify the data in the site
  • Set cookie security data to prevent third party websites from accessing the user’s cookie
  • Organize the third party website request interface
  • When the server receives the request, it verifies the authentication information, such as the verification code or token

The Node + React project is used as an example to illustrate how to verify tokens for CSRF attacks. Here we use a very mature third party package: CSURF

It should be noted that in this example, the backend uses cookies to assist in managing token information, so cookie-Parser has been used in the project. For more details, please refer to the CSURF official documentation.

From a development perspective, there are three steps:

  1. The backend API generates tokens
  2. The front-end sends a request, obtains the token and stores it locally. In subsequent requests, the token is attached to the request header
  3. After receiving the request, the back end checks whether the token in the request header is valid. If the token is valid, the back end continues to execute the request. Otherwise, the back end directly returns error information to the front end.

The token is generated in the back-end API and returned to the front-end request

First execute the script to install the Csurf package into the project:

npm install csurf
Copy the code

Then introduce the package into your project and write an API to generate the token, as shown in the following code example:

var csrf = require('csurf')

var csrfProtection = csrf({ cookie: true });
app.get(`/getCsrfToken`, csrfProtection, (req, res) = > {
    res.send({ csrfToken: req.csrfToken() });
})
Copy the code

The front-end obtains the token and adds it to the subsequent request header

In front-end projects developed with React, the token can be obtained by calling the /getCsrfToken request after the root component has been mounted, before all other requests. It is recommended that you make the request in the root component’s componentDidMount lifecycle and then save the resulting token to sessionStorage. The example code is as follows:

import axios from 'axios';

componentDidMount() {
    axios.get('/getCsrfToken')
        .then(res= > {
            if (res && res.data && res.data.csrfToken) {
                window.sessionStorage.setItem('CSRF-Token', res.data.csrfToken);
            } else {
                throw new Error("Get CSRF token failed");
            }
        }).catch(() = > {
            throw new Error("Get CSRF token failed");
        });
}
Copy the code

After obtaining the token, all other API requests will set the token in the request header and send it to the back-end API together. Here’s an example of how to set the request header in Axios:

import axios from 'axios';

// Set the request header when the AXIos instance is created
this.axios = axios.create({
    headers: {
        'CSRF-Token': window.sessionStorage.getItem('CSRF-Token') | |""}})// Modify the request header for the created AXIos instance
this.axios.defaults.headers.common['CSRF-Token'] =  window.sessionStorage.getItem('CSRF-Token');
Copy the code

In this way, when the front end sends a request, it will attach the token information to the request header and send it to the back end for processing.

Verify the validity of token information in the back-end

When generating the token information earlier, we have created a CSURF instance with the following code:

var csrfProtection = csrf({ cookie: true });
Copy the code

We can directly use the instance in the form of middleware to verify the token, that is:

app.use(csrfProtection);
Copy the code

Here, a basic measure to defend against CSRF attacks is completed. It should be noted that when using cSURF packets to defend against CSRF attacks, two variables will be checked: one is automatically added to the cookie _cSRf, and the other is the token generated above.

Write in the back

If there are any mistakes in the blog, I hope you can correct them.