Prevent Cross-Site Request Forgery Attacks
- 2 minutes to read
A Cross-Site Request Forgery (CSRF/XSRF) attack causes an authenticated browser to send unintended requests to your application endpoints. A threat actor can leverage an authenticated browser to execute these forged requests with full privileges.
ASP.NET Core includes built in protection against CSRF attacks. It generates two correlated tokens: one token is stored in a cookie, and another token is submitted in each request. When a request arrives, the framework compares these tokens. If they match, the request is processed. Otherwise the request is rejected with an HTTP 400 Bad Request status code.
CSRF protection is activated at the control level.
Protect Rich Text Editor and Spreadsheet
To activate CSRF protection for the Spreadsheet and Rich Text Editor controls, apply the following changes to your code:
On a Razor page or view, inject the anti‑forgery service.
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery AntiforgeryAdd a JavaScript function that generates and persists the cookie token and returns the associated request token.
<script> function onBeforeSend(control, e) { e.request.setRequestHeader("RequestVerificationToken", "@Antiforgery.GetAndStoreTokens(Context).RequestToken"); } </script>Tip
The default header name is
RequestVerificationToken. You can override it via AntiforgeryOptions.Pass the function name to the control’s
OnBeforeSendmethod to include the token into all internal HTTP requests:@(Html.DevExpress().RichEdit("richEdit") /** Use the following line for Razor Pages App */ .ExportUrl(Url.Page(pageName: null, pageHandler: "DxRichEditExport")) /** Use the following line for MVC Web App */ /** .ExportUrl(Url.Action("DxRichEditExport")) */ .OnBeforeSend("onBeforeSend") )Enable automatic validation of anti-forgery tokens.
Note
This steps is only required for ASP.NET Core MVC web apps. Razor Pages automatically apply anti forgery validation to all unsafe handler methods.
You can enable validation for individual actions, an entire controller, or globally:
Decorate a controller action with the ValidateAntiForgeryToken or AutoValidateAntiforgeryToken attribute.
[AutoValidateAntiforgeryToken] public IActionResult DxSpreadsheetRequest() { return SpreadsheetRequestProcessor.GetResponse(HttpContext); }Put the AutoValidateAntiforgeryToken attribute on the controller class.
[AutoValidateAntiforgeryToken] public class SpreadsheetController : Controller { public IActionResult DxSpreadsheetRequest() { return SpreadsheetRequestProcessor.GetResponse(HttpContext); } }Register a global filter in Program.cs.
services.AddControllersWithViews( o => o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()) );