Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created October 22, 2023 08:04
Show Gist options
  • Save dj-nitehawk/9c25e9b66114a93556f9931688a6fb68 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/9c25e9b66114a93556f9931688a6fb68 to your computer and use it in GitHub Desktop.
Antiforgery Token Usage
sealed class GetAfTokenEndpoint : EndpointWithoutRequest
{
public IAntiforgery Antiforgery { get; set; }
public override void Configure()
{
Get("anti-forgery-token");
AllowAnonymous();
}
public override async Task HandleAsync(CancellationToken c)
{
var tokenSet = Antiforgery.GetAndStoreTokens(HttpContext);
await SendAsync(
new
{
formFieldName = tokenSet.FormFieldName,
token = tokenSet.RequestToken
});
}
}
var bld = WebApplication.CreateBuilder();
bld.Services
.AddFastEndpoints()
.AddAntiforgery();
var app = bld.Build();
app.UseAntiForgery()
.UseFastEndpoints();
app.Run();
sealed class MyRequest
{
public string FullName { get; set; }
}
sealed class ProtectedEndpoint : Endpoint<MyRequest>
{
public override void Configure()
{
Post("protected");
AllowAnonymous();
AllowFormData(urlEncoded: true); //set false for multi-part/form-data
EnableAntiforgery();
}
public override async Task HandleAsync(MyRequest r, CancellationToken c)
{
await SendAsync(r.FullName);
}
}
###
# execute this get request to obtain an antiforgery token and cookie
GET http://localhost:5001/anti-forgery-token
###
# set the obtained token below as a form field
POST http://localhost:5001/protected
Content-Type: application/x-www-form-urlencoded
FullName = John Doe &
__RequestVerificationToken = OBTAINED_REQUEST_TOKEN_GOES_HERE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment