The detailed defense strategy for CSRF is actually implemented in the TS-AXIos library.

First, briefly:

Principle of CSRF attack

In normal cases, CSRF attacks are invalid. When xhr.withCredentials is configured to support cookie carrying in cross-domain cases, and SameSite also supports cookie carrying in cross-domain cases, cross-domain requests are hidden.

When an attacker sends a cross-domain request to forge a user, the request is forged because the user (the cookie of the request domain) can be carried in the cross-domain request.

The strategy for CSRF request defense is also simple:

After each request to the server, the server generates a token that is returned and stored on the client through set-cookie. Each time the client sends a request, the token value is parsed from the cookie and placed in the requestHeaders. The server is informed that the token value in headers is used to authenticate the user, thus achieving CSRF defense.

Because of the restriction of the same origin policy, even though the attacker can send the request by forging the request to carry the user’s cookie, the attacker can’t get the cookie specific information (it can only be carried by the request and not through the JS operation). Therefore, the forger’s request cannot read the cookie and thus sets the request header corresponding to the token. At this time, the server cannot recognize the token in the request header, so it considers this request invalid.

Note that the Token mechanism is refreshed periodically. The specific time of refreshing the Token depends on the background. Since the Token is returned in the background, the interface that needs to be authenticated will identify the user’s permission based on the Token, and if the permission is insufficient, 401(first, it will determine whether the Token exists, and secondly, it will also ask whether it is the nearest Token). So the combination of periodic refreshes of tokens and the aforementioned tokens placed in headers effectively prevents CSRF.

Let’s talk about it in detail

XSRF also known as CSRF (opens new Window), cross-site request forgery, it is a common front end attack, we first through a diagram to recognize its attack means.

CSRF has many defense methods, such as the referer of the authentication request, but the referer can also be forged, so one way to prevent such attacks is that the server side requires each request to contain a token. The token is not generated at the front end, but generated every time we visit the site. Then, when the client sends a request, it reads the token from the corresponding field in the cookie and adds it to the request headers. In this way, the server can read the token from the request headers and verify it. Since the token is difficult to forge, it can distinguish whether the request was made by the user normally.