How to add authentication to Swagger UI

  • Language:: CSharp
  • Type:: Back-end
  • Context:: Add security to the Swagger UI that is to be used in the api
  • Snippet – the actual snippet/boilerplate (wrapped in code tags)
_ = services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "AwesomeAPI", Version = "v1" });
 
        // Add security API key as parameter or header
        c.AddSecurityDefinition("apiKey", new OpenApiSecurityScheme()
        {
            Type = SecuritySchemeType.ApiKey,
            In = ParameterLocation.Header,
            Name = "ApiKey", // the name of the header to be passed in
            Scheme = "ApiKeyScheme"
        });
 
        // Add a security requirement so that the api key is sent along as a header
        OpenApiSecurityScheme key = new OpenApiSecurityScheme()
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "apiKey" // this needs to be the name of the definition above
            },
            In = ParameterLocation.Header
        };
        OpenApiSecurityRequirement requirement = new OpenApiSecurityRequirement
        {
            { key, new List<string>() }
        };
 
        c.AddSecurityRequirement(requirement);
    });

📇Additional Metadata

  • 📁Type:: snippet
  • 🏷️Tags::
  • 📡Status:: #status/🌲