How to add Api key validation in Swagger
Just a quick post on how to add api key validation in swagger docs. Pretty easy and here is the code to add in AddSwaggerGen
in the program.cs
file. You can define your own Api key validation middleware.
builder.Services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("api_key", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
Name = "Authorization",
In = ParameterLocation.Header,
Description = "API key needed to access the endpoints."
});
// Define your security requirement (optional)
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "api_key"
}
},
new string[] { }
}
});
});