Preventing CSRF (Cross-Site Request Forgery) attacks

CSRF is an attack that executes unsolicited operations on a web application on behalf of the authenticated user. Since the attacker is unable to forge the response of the request, it is implicated mostly on HTTP POST, PUT, and DELETE methods, which are used to modify the insert, update, or delete data on the server.

ASP.NET Core provides a built-in token to prevent CSRF attacks, and you can do this yourself by adding the ValidateAntiForgeryTokenAttribute filter while adding MVC in the ConfigureServices method of the Startup class. Here is the code to add an anti-forgery token globally to your ASP.NET Core application:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => { options.Filters.Add(new ValidateAntiForgeryTokenAttribute()); });
}

Alternatively, we can also add ValidateAntyForgeryToken on specific controller action methods. In that case, we don’t have to add the ValidateAntiForgeryTokenAttribute filter in the ConfigureServices method of the Startup class. Here is the code to protect the HTTP POST action method from CSRF attacks:

[HttpPost]

[ValidateAntiForgeryToken]
public async Task<IActionResult> Submit()
{
return View();
}
CORS (Cross Origin Security)

The second option is to enable CORS (Cross-Origin Security) for authenticated origins, headers, and methods. Setting CORS allows your APIs to be only accessible from configured origins. In ASP.NET Core, CORS can be easily set by adding middleware and defining its policy.

The ValidateAntiForgery attribute tells ASP.NET Core to put the token in the form, and when it’s submitted, it validates and ensures that the token is valid. This prevents your application from CSRF attacks by validating the token for every HTTP POST, PUT, and other HTTP requests, and protects the forms from being posted maliciously.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.75.221