Skip to content
Permalink
Browse files

Adds Swagger and configures auth support with Api Key in the Swagger UI

  • Loading branch information
joseftw
joseftw committed Dec 15, 2019
1 parent ed520fe commit c5fc3995e6752871989f22777a99682b12543a15
@@ -0,0 +1,40 @@
using System.Collections.Generic;
using JOS.ApiKeyAuthentication.Web.Features.Shared;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace JOS.ApiKeyAuthentication.Web.Features.Swagger
{
public static class SwaggerConfigurator
{
public static void ConfigureSwaggerFeature(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JOS.ApiKeyAuthentication", Version = "v1" });

c.AddSecurityDefinition(ApiKeyConstants.HeaderName, new OpenApiSecurityScheme
{
Description = "Api key needed to access the endpoints. X-Api-Key: My_API_Key",
In = ParameterLocation.Header,
Name = ApiKeyConstants.HeaderName,
Type = SecuritySchemeType.ApiKey
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Name = ApiKeyConstants.HeaderName,
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = ApiKeyConstants.HeaderName },
},
new string[] {}
}
});
});
}
}
}
@@ -7,6 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc5" />
<PackageReference Include="System.Text.Json" Version="4.7.0" />
</ItemGroup>

@@ -1,9 +1,9 @@
using System.Text.Json;
using JOS.ApiKeyAuthentication.Web.Features.Authentication;
using JOS.ApiKeyAuthentication.Web.Features.Authorization;
using JOS.ApiKeyAuthentication.Web.Features.Swagger;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -40,13 +40,15 @@ public void ConfigureServices(IServiceCollection services)

services.AddSingleton<IGetApiKeyQuery, InMemoryGetApiKeyQuery>();

services.AddRouting();
services.AddRouting(x => x.LowercaseUrls = true);
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.IgnoreNullValues = true;
});

services.ConfigureSwaggerFeature();
}

public void Configure(IApplicationBuilder app, IHostEnvironment env)
@@ -58,6 +60,13 @@ public void Configure(IApplicationBuilder app, IHostEnvironment env)
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "JOS.ApiKeyAuthentication");
});

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();

0 comments on commit c5fc399

Please sign in to comment.
You can’t perform that action at this time.