Skip to content

Instantly share code, notes, and snippets.

@pedroinfo
Last active November 7, 2025 13:48
Show Gist options
  • Select an option

  • Save pedroinfo/f2c66c6e94eb301048514c82dfe9c478 to your computer and use it in GitHub Desktop.

Select an option

Save pedroinfo/f2c66c6e94eb301048514c82dfe9c478 to your computer and use it in GitHub Desktop.
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private readonly string _apiKey;
private const string HeaderName = "x-api-key";
public ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
{
_next = next;
_apiKey = config["Security:ApiKey"];
}
public async Task Invoke(HttpContext context)
{
var path = context.Request.Path.Value?.ToLower();
// ✅ Permite Swagger, JSON do Swagger e arquivos estáticos
if (path!.StartsWith("/swagger") ||
path.Contains("swagger") ||
path.StartsWith("/favicon"))
{
await _next(context);
return;
}
// ✅ A partir daqui, tudo exige API Key
if (!_apiKey.HasValue())
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("API Key not configured.");
return;
}
if (!context.Request.Headers.TryGetValue(HeaderName, out var extracted))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key is missing.");
return;
}
if (!string.Equals(extracted, _apiKey))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid API Key.");
return;
}
await _next(context);
}
}
{
"Security": {
"ApiKey": "MEU-CODIGO-SECRETO"
}
}
app.UseMiddleware<ApiKeyMiddleware>();
builder.Services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("ApiKey", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = "Informe a API Key",
In = ParameterLocation.Header,
Name = "x-api-key",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference
{
Id = "ApiKey",
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme
}
},
Array.Empty<string>()
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment