diff --git a/fundamentals/minimal-apis/samples/MyAntiForgery8/MyAntiForgery.csproj b/fundamentals/minimal-apis/samples/MyAntiForgery8/MyAntiForgery.csproj new file mode 100644 index 0000000..1b28a01 --- /dev/null +++ b/fundamentals/minimal-apis/samples/MyAntiForgery8/MyAntiForgery.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/fundamentals/minimal-apis/samples/MyAntiForgery8/Program.cs b/fundamentals/minimal-apis/samples/MyAntiForgery8/Program.cs new file mode 100644 index 0000000..5fd6ec0 --- /dev/null +++ b/fundamentals/minimal-apis/samples/MyAntiForgery8/Program.cs @@ -0,0 +1,95 @@ +#define FIRST // FIRST SHORT +#if NEVER +#elif FIRST +// +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(); + +builder.Services.AddAntiforgery(); + +var app = builder.Build(); + +// +// Pass token +app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) => +{ + var token = antiforgery.GetAndStoreTokens(context); + return Results.Content(MyHtml.GenerateForm("/todo", token), "text/html"); +}); + +// Don't pass a token, fails +app.MapGet("/SkipToken", (HttpContext context, IAntiforgery antiforgery) => +{ + var token = antiforgery.GetAndStoreTokens(context); + return Results.Content(MyHtml.GenerateForm("/todo",token, false ), "text/html"); +}); + +// Post to /todo2. DisableAntiforgery on that endpoint so no token needed. +app.MapGet("/DisableAntiforgery", (HttpContext context, IAntiforgery antiforgery) => +{ + var token = antiforgery.GetAndStoreTokens(context); + return Results.Content(MyHtml.GenerateForm("/todo2", token, false), "text/html"); +}); + +// +app.MapPost("/todo", ([FromForm] Todo todo) => Results.Ok(todo)); + +app.MapPost("/todo2", ([FromForm] Todo todo) => Results.Ok(todo)) + .DisableAntiforgery(); +// +// + +app.Run(); + +class Todo +{ + public required string Name { get; set; } + public bool IsCompleted { get; set; } + public DateTime DueDate { get; set; } +} + +public static class MyHtml +{ + // + public static string GenerateForm(string action, + AntiforgeryTokenSet token, bool UseToken=true) + { + string tokenInput = ""; + if (UseToken) + { + tokenInput = $@""; + } + + return $@" + +
+ {tokenInput} + + + + +
+ + "; + } + //
+} +//
+#elif SHORT +// +var builder = WebApplication.CreateBuilder(); + +builder.Services.AddAntiforgery(); + +var app = builder.Build(); + +app.UseAntiforgery(); + +app.MapGet("/", () => "Hello World!"); + +app.Run(); +// +#endif diff --git a/fundamentals/minimal-apis/samples/MyAntiForgery8/appsettings.json b/fundamentals/minimal-apis/samples/MyAntiForgery8/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/fundamentals/minimal-apis/samples/MyAntiForgery8/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}