Thursday 5 September 2024

Implement Authorization in Swagger with Static Value in Header .Net 8

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


app.UseMiddleware<ApiKeyMiddleware>();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
app.Run();


Step 4: Add  ApiKey in appsettings.json

"ApiKey": "setia",


Step 5: Run the application and you will Notice you can see the Authorize button in the top right position on Swagger.










Step 6: On the Click of a button, it will ask you to enter the key here. It will match the key mentioned in the app settings.json
























Step 7: It will match the key mentioned in the app settings.json. If the passed key is incorrect or you run the endpoint without a key it will throw an 401 Error.





















You will get the response if the key is correct.




Implement Authorization in Swagger with Static Value in Header .Net 8

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 head...