What is CSRF?
CSRF (Cross-site request forgery), also known as one click attack/session riding, Chinese abbreviation: CSRF/XSRF. CSRF (Cross Site Request Forgery) is a network attack method that was listed as one of the top 20 security risks on the Internet in 2007. Other security risks, such as SQL script injection and cross-site domain script attacks, have become well-known in recent years, and many websites have defended against them. However, CSRF is still a foreign concept to most people. Even the most famous Gmail had a CSRF vulnerability in late 2007, which was hacked and caused huge losses to Gmail users.
What can CSRF do?
You can understand CSRF attacks like this: an attacker has stolen your identity and sent malicious requests in your name. CSRF can do things like send emails, send messages, steal your account, or even buy goods and transfer virtual currency on your behalf...... The problems caused include: personal privacy leakage and property security.
ASP.NET MVC AntiForgeryToken anti-counterfeiting mark
In ASP.NET MVC, form tokens and cookie tokens are automatically generated by default whenever @Html.AntiForgeryToken() is used in the view page. However, if we want to achieve manual retrieval in the background, we need to use the System.Web.Helpers.AntiForgery class, and friends who are interested in viewing the source code will find that in fact, the method of internal call of @Html.AntiForgeryToken() is the same as that of the AntiForgery class.
It is mainly used to obtain the corresponding form and cookie token through two static methods: AntiForgery.GetHtml() or AntiForgery.GetTokens(string oldCookieToken, out string newCookieToken, out string formToken). However, it should be noted that once the GetHtml method is called, the corresponding cookie token will be automatically generated, and then a piece of HTML code with the form token value hidden field will be returned directly, and the returned value will be in this form:
<input name="__RequestVerificationToken" type="hidden" value="8_nUk_3z0svQr9qcvRBi9SWMZ2-SYmuy9kRe9OgRobGULkb2Z4JZxRZFhR0ndeoy9hmDLDru7MFk-W4xrnL5z5T6VbkfXK7fyRk-egQBGm41"> The name name of the hidden field is generally fixed to "__RequestVerificationToken", and the value is an encrypted security token. This hidden field is usually placed in the form to be submitted, and the final submission is verified against the cookie token.
If you use the GetTokens method, you can obtain the encrypted form and cookie token after passing in the corresponding parameters, but here you need to store the corresponding values yourself.
Next, we will introduce the method of manually updating AntiForgeryToken, mainly through AJAX.
Package Code:
Test code:
We found that when sending an ajax request, __RequestVerificationToken parameters are automatically included, as shown in the figure below:
|