Accessible forms and antiforgery
Accessible forms and antiforgery
An accessible form gives every control a meaningful label, supports keyboard operation, and communicates validation errors in text. Antiforgery protects state-changing browser requests against cross-site request forgery (CSRF), particularly when browsers automatically attach authentication cookies. The server verifies a request token together with an associated cookie; a visible form alone is not protection.
A label whose for attribute matches the input id gives the control an accessible name. Use native buttons, logical focus order and text errors tied to fields (for example aria-describedby); do not rely on color or placeholders alone. Input and Label Tag Helpers can generate matching names and IDs. A validation summary helps users find errors. Razor Pages normally validates antiforgery for unsafe requests; MVC actions can apply ValidateAntiForgeryToken, or configure AutoValidateAntiforgeryToken globally for unsafe methods. A POST form using Form Tag Helper can generate a token. Do not disable validation to make a test pass. CSRF protection does not replace authentication, record-level authorization, XSS prevention or input validation. This local HTTP fixture uses test-only cookies, not a production HTTPS configuration.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Inspect label and error associations
The GET request verifies that generated HTML has a label, input and error description. This is a markup check, not a full accessibility audit.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddRazorPages();await using var app = builder.Build();app.MapRazorPages();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/Request", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.IsSuccessStatusCode && body.Contains("for=\"Title\"") && body.Contains("id=\"Title\"") && body.Contains("aria-describedby=\"title-error\"") && body.Contains("id=\"title-error\""), "label and error linkage"); Console.WriteLine("label and error linkage");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Companion source files (place under the project root exactly as named):
Pages/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersPages/Request.cshtml
@page@model RequestModel<!doctype html><html lang="en"><head><title>Request a book</title></head><body><main><h1>Request a book</h1><form method="post"> <div asp-validation-summary="All"></div> <label asp-for="Title"></label> <input asp-for="Title" aria-describedby="title-error" /> <span id="title-error" asp-validation-for="Title"></span> <button type="submit">Request</button></form>@if (Model.Accepted) { <p>Request accepted</p> }</main></body></html>Pages/Request.cshtml.cs
using System.ComponentModel.DataAnnotations;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public sealed class RequestModel : PageModel{ [BindProperty, Required(ErrorMessage = "Enter a title."), StringLength(40)] public string? Title { get; set; } public bool Accepted { get; private set; } public void OnGet(bool accepted = false) => Accepted = accepted; public IActionResult OnPost() { if (!ModelState.IsValid) return Page(); // No persistence in this lab; the redirect is a UI demonstration. return RedirectToPage(new { accepted = true }); }}Expected console observation (unexecuted):
label and error linkageThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Reject a missing request token
The client fetches the form so it has a cookie, but submits no request token. The unsafe request should fail before OnPost.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddRazorPages();await using var app = builder.Build();app.MapRazorPages();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var page = await client.GetAsync("/Request", deadline.Token); page.EnsureSuccessStatusCode(); using var form = new FormUrlEncodedContent(new Dictionary<string, string> { ["Title"] = "River Atlas" }); using var response = await client.PostAsync("/Request", form, deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.StatusCode == HttpStatusCode.BadRequest, "missing token rejected"); Console.WriteLine("missing token rejected");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Companion source files (place under the project root exactly as named):
Pages/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersPages/Request.cshtml
@page@model RequestModel<!doctype html><html lang="en"><head><title>Request a book</title></head><body><main><h1>Request a book</h1><form method="post"> <div asp-validation-summary="All"></div> <label asp-for="Title"></label> <input asp-for="Title" aria-describedby="title-error" /> <span id="title-error" asp-validation-for="Title"></span> <button type="submit">Request</button></form>@if (Model.Accepted) { <p>Request accepted</p> }</main></body></html>Pages/Request.cshtml.cs
using System.ComponentModel.DataAnnotations;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public sealed class RequestModel : PageModel{ [BindProperty, Required(ErrorMessage = "Enter a title."), StringLength(40)] public string? Title { get; set; } public bool Accepted { get; private set; } public void OnGet(bool accepted = false) => Accepted = accepted; public IActionResult OnPost() { if (!ModelState.IsValid) return Page(); // No persistence in this lab; the redirect is a UI demonstration. return RedirectToPage(new { accepted = true }); }}Expected console observation (unexecuted):
missing token rejectedThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Protect a controller POST
A controller explicitly requires antiforgery. The form generates the token; the same cookie-enabled client sends it back. The protected action does no real writes.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddControllersWithViews();await using var app = builder.Build();app.MapControllers();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var formResponse = await client.GetAsync("/reserve", deadline.Token); formResponse.EnsureSuccessStatusCode(); var html = await formResponse.Content.ReadAsStringAsync(deadline.Token); // Narrow extraction for this lab's generated form, not a general HTML parser. var input = Regex.Matches(html, "<input\\b[^>]*>", RegexOptions.IgnoreCase) .Cast<Match>().Single(m => m.Value.Contains("name=\"__RequestVerificationToken\"")); var token = WebUtility.HtmlDecode(Regex.Match(input.Value, "value=\"([^\"]+)\"").Groups[1].Value); Check(!string.IsNullOrEmpty(token), "token exists"); using var form = new FormUrlEncodedContent(new Dictionary<string,string> { ["__RequestVerificationToken"] = token }); using var response = await client.PostAsync("/reserve", form, deadline.Token); Check(response.IsSuccessStatusCode && (await response.Content.ReadAsStringAsync(deadline.Token)) == "received", "protected controller POST"); Console.WriteLine("protected controller POST");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}public sealed class ReserveController : Controller{ [HttpGet("/reserve")] public IActionResult Index() => View(); [HttpPost("/reserve"), ValidateAntiForgeryToken] public IActionResult Submit() => Content("received");}Companion source files (place under the project root exactly as named):
Views/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersViews/Reserve/Index.cshtml
<h1>Reserve a book</h1><form asp-controller="Reserve" asp-action="Submit" method="post"><button type="submit">Reserve</button></form>Expected console observation (unexecuted):
protected controller POSTThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
A token in HTML without server validation is insufficient. A cookie alone is not the request token. Never expose tokens in logs or URLs; never use real session credentials in fixtures. Test keyboard navigation and a screen reader in addition to generated markup. A successful CSRF test does not establish authorization or security of the application.
Practice and recap
Design an accessible quantity form with an associated error message. List tests for missing token, invalid quantity with valid token, and unauthorized access with valid token.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Accessible forms and antiforgery — knowledge check
Apply the lesson concepts to the following scenarios.
What should a label for match?
Why add aria-describedby?
What should happen when a protected POST lacks its request token?
What does a valid antiforgery token prove?
What is a meaningful accessibility test beyond inspecting HTML?