Interview Question: What is a CSRF attack and how to avoid it

Interview Question: What is a CSRF attack and how to avoid it

CSRF (Cross-site Request Forgery) attack refers to an attack method in which an attacker induces users to perform involuntary operations on trusted websites, thereby gaining unauthorized access or manipulating permissions. The attacker will use the existing login session to call certain functions that need to exist on the attacked website, so as to achieve the goal of deceiving the user/server.

For example, attackers can use CSRF attacks to send malicious requests to the server with the user's logged-in identity (cookie information) in scenarios such as blogs and email accounts, and delete, modify, and add operations to the website.

There are two main ways to avoid CSRF:

  1. Clarify the data range: When using the HTTP protocol to request, in order to prevent Cross-site Request, you need to add a random token in the HTTP request header as a check code, and compare the value of the token on the server side with the value stored in the cookie. If different, reject the request.

  2. Reasonably set cookies and sessions: When user A visits the website, the system generates a Session in the background, returns the Session ID to the browser, and stores it in a cookie, and sends the cookie to the server next time it visits, so here we need Make the following restrictions:
    a. Set cookie attributes such as HttpOnly, prohibit page JavaScript from accessing cookies, and improve cookie security;
    b. End sessions in time: prevent Session Fixation and other situations from happening;

To sum up, in order to prevent CSRF attacks, we should develop a good habit of using cookies with the HttpOnly attribute and storing data ranges in cookies and requesting random tokens. In addition, it is also an effective way to properly design the url structure to limit user form submissions .

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/131141652