Created
October 22, 2023 08:04
-
-
Save dj-nitehawk/9c25e9b66114a93556f9931688a6fb68 to your computer and use it in GitHub Desktop.
Antiforgery Token Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bld = WebApplication.CreateBuilder(); | |
bld.Services | |
.AddFastEndpoints() | |
.AddAntiforgery(); | |
var app = bld.Build(); | |
app.UseAntiForgery() | |
.UseFastEndpoints(); | |
app.Run(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# 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