skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

HTMX Requests with ASP.NET Core Anti-Forgery Tokens

Pass anti-forgery tokens on every HTMX request, including DELETE and boosted navigation, to an ASP.NET Core backend with HTMX.NET 1.13.

7 min read Updated

HTMX is a JavaScript library designed to work with various HTTP methods: GET, POST, PUT, and DELETE. Three out of the four methods, excluding the GET method, are meant to cause side effects and mutations on the server: update a shopping cart, complete an order, upload a file, etc. Endpoints that perform modifications are also vulnerable to cross-site request forgery attacks. A malicious party may cause a trusted user to submit information on their behalf to trigger an unwanted action. For example, a hacker may target an insecure form on a banking site, trying to get bank members to transfer funds inadvertently. Hackers can embed these insecure forms in spam emails, dangerous websites, or part of some malware attack.

The safest approach to mitigate these attacks is to include an anti-forgery request token with every request. Keep request tokens on your own origin, because exposing one to another site can undermine CSRF protection. Then, the application verifies the token using a combination of cookies, form inputs, and header values. It is a technique found in many technology stacks, including ASP.NET Core.

Updated November 2026: HTMX.NET 1.13.0 sends the token for you, and the post now covers htmx 2, boosted navigation, and DELETE.

HTMX users often hit the anti-forgery error on POST, PUT, PATCH, and DELETE calls. The solution is to pass the token, and HTMX.NET (documentation) can do that with two tags and one endpoint. The examples target htmx 2.x (2.0.11 at the time of writing). htmx 4 needs a different HTMX.NET release, covered at the end.

The HTMX.NET setup

You need HTMX.NET 1.13.0 or later, which includes the fixes described below. See the 1.13.0 release notes.

Terminal window
dotnet add package Htmx.TagHelpers --version 1.13.0

Add the tag helpers to your Razor _ViewImports.cshtml.

@addTagHelper *, Htmx.TagHelpers

Map the script endpoint in Program.cs.

app.MapHtmxAntiforgeryScript(); // serves /_htmx/antiforgery.js

Then add the meta tag and the scripts to the <head> of your _Layout.cshtml. The @@ is Razor’s escape for @.

<meta name="htmx-config" includeAspNetAntiforgeryToken="true" />
<script src="https://unpkg.com/htmx.org@@2.0.11/dist/htmx.min.js" defer></script>
<script src="@HtmxAntiforgeryScriptEndpoints.Path" defer></script>

The tag helper adds an antiForgery object to the htmx-config content with formFieldName, headerName, and requestToken. The script reads it and attaches the token to every unsafe request. Boosts never reload the head, so the script runs once. If you’d rather inline it, @Html.HtmxAntiforgeryScript() emits the same script.

That’s it. Buttons, div elements, and forms with hx-post, hx-put, hx-patch, and hx-delete all validate without wrapping anything in a form just to get the hidden input.

What changed in HTMX.NET 1.13.0?

The 1.12.0 script had several problems, most visible on htmx 2. Version 1.13.0 fixes them.

  • The header is always sent. The rendered form copy of the token is stripped from the request. In 1.12.0, a <form hx-delete> skipped the header because the form field existed, and the request failed with a 400.
  • The token never lands in a URL. htmx 2 sends DELETE parameters in the query string, and GET forms do too. ASP.NET Core doesn’t read tokens from the query string, and URLs leak through logs, history, and Referer headers.
  • Same-origin only. The token is attached only when the target resolves, against document.baseURI, to the page’s origin. A <base href> can’t slip a request to another origin past the check. Rendered token fields are stripped from cross-origin requests too.
  • No more response-text refresh. 1.12.0 parsed boosted responses and trusted any htmx-config meta tag it found, which let an attacker-influenced fragment replace your token.
  • selfRequestsOnly is no longer forced to false. In 1.12.0, the config tag helper rendered "selfRequestsOnly":false on every page, which turned off htmx 2’s default block on cross-origin requests. Apps on 1.12.0 and htmx 2 weren’t protected by that default. In 1.13.0 the tag helper leaves htmx’s default alone.

Redirects are the one remaining risk. If your app has an open redirect, a token-bearing request to it can be forwarded to another origin through a 307 or 308. Don’t expose open redirects.

What behavior changes in 1.13.0?

Refresh the page after sign-in or sign-out

Boosted links swap the <body> and leave the <head> alone, so the token from the first full page load stays in place. That’s fine until the user’s identity changes. A token generated for an anonymous user fails validation for the signed-in one, and the next unsafe request returns a 400.

Tokens refresh on full page loads, so force one after the identity changes with the HX-Refresh response header. Do it in the handler that changes the identity, and keep that handler a POST. Razor Pages validates the antiforgery token on POST handlers by default, so the sign-in itself stays protected.

// an htmx POST to ?handler=SignIn (the HTMX.NET script adds the antiforgery header)
public async Task<IActionResult> OnPostSignInAsync()
{
// verify the user's credentials and build their ClaimsPrincipal first (omitted)
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
// reload the page so the layout renders a token for the new identity
Response.Htmx(h => h.Refresh()); // sends HX-Refresh: true
return new EmptyResult();
}

Refresh() comes from the Htmx package. Without it, set Response.Headers["HX-Refresh"] = "true". A redirect that isn’t boosted works too. Never sign users in or out from a GET handler; that’s a CSRF hole the antiforgery token can’t cover.

Cross-origin requests are opt-in

With htmx 2, requests to other origins are blocked. If you need them, say so explicitly. The token still isn’t sent to them.

<meta name="htmx-config" selfRequestsOnly="false" includeAspNetAntiforgeryToken="true" />

Form-field mode and DELETE fail closed

ASP.NET Core sends a header name by default, and header mode is unaffected by any of this. If you set AntiforgeryOptions.HeaderName to null, HTMX.NET falls back to the form field. On htmx 2, DELETE parameters go in the URL, so the script refuses to send the token. The request returns a 400 and the console logs Antiforgery token not sent for DELETE…. There are two fixes. Keep the default header name, or make DELETE send a body like htmx 1 did.

<meta name="htmx-config" includeAspNetAntiforgeryToken="true"
methodsThatUseUrlParams='new[] { "get" }' />

What if I can’t use the HTMX.NET package?

You can write the listener yourself. This version matches the 1.13.0 script and works on htmx 1.x and 2.x.

if (!window.__htmxAntiforgery) {
window.__htmxAntiforgery = true;
const safeMethods = ["GET", "HEAD", "OPTIONS", "TRACE"];
document.addEventListener("htmx:configRequest", (evt) => {
const antiForgery = htmx.config.antiForgery;
if (!antiForgery) return;
const verb = evt.detail.verb.toUpperCase();
let sameOrigin = false;
try {
sameOrigin = new URL(evt.detail.path, document.baseURI).origin
=== window.location.origin;
} catch (e) {
sameOrigin = false;
}
// safe methods and other origins never get the token, even from a rendered form
if (safeMethods.includes(verb) || !sameOrigin) {
if (antiForgery.formFieldName) delete evt.detail.parameters[antiForgery.formFieldName];
return;
}
if (!antiForgery.requestToken) return;
if (antiForgery.headerName) {
evt.detail.headers[antiForgery.headerName] = antiForgery.requestToken;
// drop the rendered form copy so htmx 2 can't put it in the query string
if (antiForgery.formFieldName) delete evt.detail.parameters[antiForgery.formFieldName];
return;
}
if (!antiForgery.formFieldName) return;
// form-field mode: never put the token in a URL
const urlParamMethods = (htmx.config.methodsThatUseUrlParams || ["get", "delete"])
.map(m => String(m).toUpperCase());
if (urlParamMethods.includes(verb)) {
delete evt.detail.parameters[antiForgery.formFieldName];
console.warn("Antiforgery token not sent for " + verb + ": htmx sends its parameters "
+ "in the URL. Configure an antiforgery header name or set "
+ "htmx.config.methodsThatUseUrlParams = [\"get\"].");
return;
}
if (!evt.detail.parameters[antiForgery.formFieldName]) {
evt.detail.parameters[antiForgery.formFieldName] = antiForgery.requestToken;
}
});
}

You still need the meta tag from the setup above. The window flag keeps the handler from registering twice if the script runs again. Don’t try to refresh the token by parsing boosted response text. Use HX-Refresh as described earlier.

Do these snippets work with htmx 4?

No. htmx 4 uses fetch() instead of XMLHttpRequest and renames the events: htmx:configRequest becomes htmx:config:request, and htmx:afterOnLoad becomes htmx:after:request. Read the htmx 4 migration guide before upgrading. htmx 4 users should use HTMX.NET 2.0.0-preview.2 or later (release notes), which also fixes the token leaks on that line.

The general (non-htmx) fix for the antiforgery token not provided error will be covered in an upcoming dedicated guide (publishing soon).

I hope you found this post helpful, and thank you for reading.

Comments

Related Posts