Technology Sharing

Front-end interview question 50 (What are some common front-end security measures to prevent CSRF attacks?)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

insert image description here
In order to prevent Cross-Site Request Forgery (CSRF) attacks, the following common security measures can be taken in front-end development:

1. Using CSRF Token

This is one of the most commonly used defense mechanisms.

  • Generate Token: After the user logs in, the server generates a random, unpredictable CSRF Token and stores it on the server side. It is also sent to the client through the Set-Cookie header and stored in the user's cookie.

  • Form Embed Token: In each HTML form that needs protection, add a hidden field (<input type="hidden">), whose value is set to the CSRF Token read from the cookie.

  • Verify Token: When the form is submitted, the backend receives the form data and the token in the cookie (due to the same-origin policy, the browser automatically sends the cookie). The server verifies whether the token in the form is consistent with the token stored on the server or in the session. If they are inconsistent, the request is rejected.

2. Verify HTTP Referer and Origin Headers

Although it is not completely reliable because the Referer and Origin may be tampered with or missing, it can still be used as an auxiliary means in some scenarios.

  • Check Referer: Verify the Referer field in the HTTP request header to ensure that the request is initiated from the expected domain name. However, please note that this method has limitations. For example, in the downgrade request from HTTPS to HTTP, the Referer will not be sent.

  • Check the Origin Header: Similar to Referer, the Origin header provides information about the origin of the request, but is only sent when using the XMLHttpRequest or Fetch API.

3. Use the SameSite Cookie Attribute

For cookies that do not require cross-site access, the SameSite attribute can be set to enhance security.

  • SameSite=Lax: Cookies are only sent in same-site requests, partially protecting against CSRF.
  • SameSite=Strict: Cookies are only sent within the same site and on the same page, providing stronger protection, but may affect some expected cross-subdomain functions.
  • SameSite=None: The Secure attribute needs to be used with cookies that need to be cross-site to meet the requirements of modern browsers.

4. Custom request header verification

Add a custom HTTP header to the AJAX request (such asX-Requested-With: XMLHttpRequest), and then verify the existence and value of this header on the server side. Because JavaScript can freely set the header of XMLHttpRequest, while ordinary form submission cannot, this can distinguish requests initiated by scripts.

Sample code (CSRF Token implementation):

Server side (pseudo code):

// 生成并设置Token
function generateCsrfToken() {
    return crypto.randomBytes(32).toString('hex');
}

app.post('/login', (req, res) => {
    const token = generateCsrfToken();
    res.cookie('csrfToken', token, { httpOnly: true, secure: true, sameSite: 'strict' });
    // 存储token到session或其他存储机制
});

app.post('/submitForm', (req, res) => {
    if (req.body.csrfToken === req.cookies.csrfToken) {
        // 请求合法,处理逻辑...
    } else {
        // CSRF攻击检测,拒绝请求
        res.status(403).send('Forbidden');
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

Front-end HTML:

<form action="/submitForm" method="POST">
    <!-- 其他表单字段... -->
    <input type="hidden" name="csrfToken" value="{{csrfToken}}">
    <button type="submit">Submit</button>
</form>
  • 1
  • 2
  • 3
  • 4
  • 5

Please note that the above code is only an example and needs to be adjusted in actual applications according to the backend framework and language used.