Last active
April 5, 2025 13:49
-
-
Save dj-nitehawk/4efe5ef70f813aec2c55fff3bbb833c0 to your computer and use it in GitHub Desktop.
API Key Authentication With FastEndpoints + Swagger
This file contains hidden or 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 ApikeyAuth(IOptionsMonitor<AuthenticationSchemeOptions> options, | |
ILoggerFactory logger, | |
UrlEncoder encoder, | |
IConfiguration config) | |
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder) | |
{ | |
internal const string SchemeName = "ApiKey"; | |
internal const string HeaderName = "x-api-key"; | |
readonly string _apiKey = config["Auth:ApiKey"] ?? throw new InvalidOperationException("Api key not set in appsettings.json"); | |
protected override Task<AuthenticateResult> HandleAuthenticateAsync() | |
{ | |
Request.Headers.TryGetValue(HeaderName, out var extractedApiKey); | |
if (!IsPublicEndpoint() && !extractedApiKey.Equals(_apiKey)) | |
return Task.FromResult(AuthenticateResult.Fail("Invalid API credentials!")); | |
var identity = new ClaimsIdentity( | |
claims: new[] { new Claim("ClientID", "Default") }, | |
authenticationType: Scheme.Name); | |
var principal = new GenericPrincipal(identity, roles: null); | |
var ticket = new AuthenticationTicket(principal, Scheme.Name); | |
return Task.FromResult(AuthenticateResult.Success(ticket)); | |
} | |
bool IsPublicEndpoint() | |
=> Context.GetEndpoint()?.Metadata.OfType<AllowAnonymousAttribute>().Any() is null or true; | |
} |
This file contains hidden or 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 Endpoint : EndpointWithoutRequest | |
{ | |
public override void Configure() | |
{ | |
Get("/protected"); | |
} | |
public override async Task HandleAsync(CancellationToken ct) | |
{ | |
await SendAsync("you are authorized!"); | |
} | |
} |
This file contains hidden or 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
using FastEndpoints; | |
using FastEndpoints.Swagger; | |
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.Extensions.Options; | |
using NSwag; | |
using System.Security.Claims; | |
using System.Security.Principal; | |
using System.Text.Encodings.Web; | |
var bld = WebApplication.CreateBuilder(); | |
bld.Services | |
.AddFastEndpoints() | |
.AddAuthorization() | |
.AddAuthentication(ApikeyAuth.SchemeName) | |
.AddScheme<AuthenticationSchemeOptions, ApikeyAuth>(ApikeyAuth.SchemeName, null); | |
bld.Services | |
.SwaggerDocument(o => | |
{ | |
o.EnableJWTBearerAuth = false; | |
o.DocumentSettings = s => | |
{ | |
s.AddAuth(ApikeyAuth.SchemeName, new() | |
{ | |
Name = ApikeyAuth.HeaderName, | |
In = OpenApiSecurityApiKeyLocation.Header, | |
Type = OpenApiSecuritySchemeType.ApiKey, | |
}); | |
}; | |
}); | |
var app = bld.Build(); | |
app.UseAuthentication() | |
.UseAuthorization() | |
.UseFastEndpoints() | |
.UseSwaggerGen(); | |
app.Run(); |
work like a charm ;)
working Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nvm, I was missing the
FastEndpoints.Swagger
reference: