AddXApiKeySecurity Method
Definition
- Namespace
- Codebelt.Extensions.Swashbuckle.AspNetCore
- Assemblies
- Codebelt.Extensions.Swashbuckle.AspNetCore.dll
AddXApiKeySecurity(SwaggerGenOptions)
Adds support for first line of defense using security based HTTP X-Api-Key header.
public static SwaggerGenOptions AddXApiKeySecurity(this SwaggerGenOptions options)
Parameters
optionsSwaggerGenOptionsThe SwaggerGenOptions to extend.
Returns
- SwaggerGenOptions
A reference to
optionsso that additional calls can be chained.
Examples
Document API Key authentication using the standard X-API-Key header. Call this extension method within AddSwaggerGen to declare API Key as a supported security scheme in the OpenAPI specification. The extension automatically creates a security scheme definition and a global security requirement, so all endpoints automatically inherit this authentication requirement and the Swagger UI shows the key header as required:
using System;
using Codebelt.Extensions.Swashbuckle.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace MySwaggerExample;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddXApiKeySecurity();
});
var app = builder.Build();
if (string.Equals(app.Environment.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers();
app.Run();
}
}