If you want an anonymous user should not run the APIs.
To run your API Endpoints From Swagger / Postman / Code the user should pass the header key. Follow the below steps.
We need to set up, AddSecurityDefinition and AddSecurityRequirement
Step 1: Open Program.cs, Copy and Paste code below
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
// Add the security requirement
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Name = "X-api-key",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Description = "API Key needed to access the endpoints."
});
// Apply the security requirement globally
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
}
},
new string[] {}
}
});
});
Step 2: Create a new Middleware Class and call in the Program.cs
public class ApiKeyMiddleware
{
private const string ApiKeyHeaderName = "X-api-key";
private readonly RequestDelegate _next;
private readonly string _apiKey;
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_apiKey = configuration["ApiKey"]; // Assuming you store the API key in your app settings
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var providedApiKey))
{
if (providedApiKey == _apiKey)
{
await _next(context);
return;
}
}
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync("Unauthorized");
}
}
Step 3: Copy these lines and paste the below lines into the Program.cs
public class ApiKeyMiddleware
{
private const string ApiKeyHeaderName = "X-api-key";
private readonly RequestDelegate _next;
private readonly string _apiKey;
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_apiKey = configuration["ApiKey"]; // Assuming you store the API key in your app settings
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var providedApiKey))
{
if (providedApiKey == _apiKey)
{
await _next(context);
return;
}
}
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync("Unauthorized");
}
}
Step 3: Copy these lines and paste the below lines into the Program.cs
No comments:
Post a Comment