Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created November 21, 2025 05:57
Show Gist options
  • Select an option

  • Save dj-nitehawk/84fe7b3a69d65e92a94f95e42c962f9e to your computer and use it in GitHub Desktop.

Select an option

Save dj-nitehawk/84fe7b3a69d65e92a94f95e42c962f9e to your computer and use it in GitHub Desktop.
Using a Test/Mock Authentication Handler With Integration Tests
var bld = WebApplication.CreateBuilder(args);
bld.Services
.AddAuthenticationJwtBearer(s => s.SigningKey = bld.Configuration["Auth:JwtKey"])
.AddAuthorization()
.AddFastEndpoints();
var app = bld.Build();
app.UseAuthentication()
.UseAuthorization()
.UseFastEndpoints();
app.Run();
[HttpPost("/protected-endpoint")]
sealed class Endpoint : EndpointWithoutRequest<string>
{
public override async Task HandleAsync(CancellationToken c)
{
await Send.OkAsync("You have access to a protected endpoint");
}
}
public class TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> o, ILoggerFactory l, UrlEncoder e)
: AuthenticationHandler<AuthenticationSchemeOptions>(o, l, e)
{
internal const string SchemeName = "Test";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
//create a test identity and auth ticket to allow test access to all endpoints
var identity = new ClaimsIdentity(
[
new(ClaimTypes.NameIdentifier, "Test-User"),
new(ClaimTypes.Name, "Test User")
],
SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
public class App : AppFixture<Program>
{
protected override void ConfigureServices(IServiceCollection s)
{
//set "Test" scheme as the default scheme and register the test handler
s.AddAuthentication(TestAuthHandler.SchemeName)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.SchemeName, null);
}
}
public class Tests(App App) : TestBase<App>
{
[Fact]
public async Task Test_Can_Access_Endpoint()
{
var (rsp, res) = await App.Client.GETAsync<Endpoint, string>();
rsp.StatusCode.ShouldBe(HttpStatusCode.OK);
res.ShouldBe("You have access to a protected endpoint");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment