Link Search Menu Expand Document

Cross-Site Request Forgery in .NET

Play SecureFlag Play .NET Labs on this vulnerability with SecureFlag!

Prevention

ASP.NET Core includes three filters for working with antiforgery tokens:

  • ValidateAntiForgeryToken
  • AutoValidateAntiforgeryToken
  • IgnoreAntiforgeryToken

ValidateAntiForgeryToken is an action filter that can be applied to an individual action, a controller, or globally. Requests made to actions that have this filter applied are blocked unless the request includes a valid anti-forgery token.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task  <iactionresult> RemoveLogin(RemoveLoginViewModel account)
{
    ManageMessageId message = ManageMessageId.Error;
    var user = await GetCurrentUserAsync();
    if (user != null) {
        var result = await _userManager.RemoveLoginAsync(
            user, account.LoginProvider, account.ProviderKey
        );
        if (result.Succeeded) {
             await _signInManager.SignInAsync(user, isPersistent: false);
             message = ManageMessageId.RemoveLoginSuccess;
        }
    }
   return RedirectToAction(nameof(ManageLogins), new { Message = message });
}

The ValidateAntiForgeryToken attribute requires a token for requests to the action methods it decorates, including HTTP GET requests. If the ValidateAntiForgeryToken attribute is applied across the app’s controllers, it can be overridden with the IgnoreAntiforgeryToken attribute.

The AutoValidateAntiforgeryToken filter works identically to the ValidateAntiForgeryToken attribute, except that it doesn’t require tokens for requests made using the following HTTP methods:

  • GET
  • HEAD
  • OPTIONS
  • TRACE

References

OWASP - Cross-Site Request Forgery Cheat Sheet Microsoft - Preventing Cross-Site Request Forgery Attacks MITRE - CWE 352