Skip to content

Antiforgery

Antiforgery token configuration protects against Cross-Site Request Forgery (CSRF) attacks by validating unique tokens for state-changing requests (POST, PUT, DELETE, etc.).

Overview

json
json
{
  "Antiforgery": {
    "Enabled": false,
    "CookieName": null,
    "FormFieldName": "__RequestVerificationToken",
    "HeaderName": "RequestVerificationToken",
    "SuppressReadingTokenFromFormBody": false,
    "SuppressXFrameOptionsHeader": false
  }
}

Settings Reference

SettingTypeDefaultDescription
EnabledboolfalseEnable antiforgery token validation.
CookieNamestringnullCustom cookie name. Uses default (.AspNetCore.Antiforgery.*) if null.
FormFieldNamestring"__RequestVerificationToken"Name of the hidden form field containing the token.
HeaderNamestring"RequestVerificationToken"HTTP header name for sending the token (useful for AJAX requests).
SuppressReadingTokenFromFormBodyboolfalseWhen true, skips reading tokens from form body (forces header-only validation).
SuppressXFrameOptionsHeaderboolfalseWhen true, disables the automatic X-Frame-Options: SAMEORIGIN header.

Token Submission

Antiforgery tokens can be submitted in two ways:

Form Field

Include a hidden field in HTML forms:

html
html
<form method="POST" action="/api/submit">
  <input type="hidden" name="__RequestVerificationToken" value="token-value" />
  <!-- form fields -->
</form>

HTTP Header

Send the token in a header (useful for AJAX/fetch requests):

javascript
javascript
fetch('/api/submit', {
  method: 'POST',
  headers: {
    'RequestVerificationToken': tokenValue
  }
});

X-Frame-Options Header

When SuppressXFrameOptionsHeader is false (default), the server automatically adds the X-Frame-Options: SAMEORIGIN header to prevent clickjacking attacks. While Antiforgery is enabled, the Security Headers middleware skips its own XFrameOptions value.

WARNING

Only set SuppressXFrameOptionsHeader to true if you're handling frame protection elsewhere (e.g., Content-Security-Policy frame-ancestors directive).

Example Configuration

Enable antiforgery with custom header name:

json
json
{
  "Antiforgery": {
    "Enabled": true,
    "HeaderName": "X-CSRF-Token",
    "SuppressReadingTokenFromFormBody": true
  }
}

Next Steps

Comments