netmash/NDB.Extensions.Swagger/SwaggerExtensions.cs

103 lines
3.8 KiB
C#
Raw Normal View History

2020-12-20 22:31:53 +02:00
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using NDB.Extensions.Swagger.Constants;
using NDB.Extensions.Swagger.Filters;
using NDB.Extensions.Swagger.ReverseProxy;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
namespace NDB.Extensions.Swagger
{
public static class SwaggerExtensions
{
public static IServiceCollection AddSwagger(this IServiceCollection services, string title, AuthorizationType authorizationType = AuthorizationType.Basic)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo
{
Title = title,
Version = "v1"
});
c.SetAuthorization(authorizationType);
c.OperationFilter<PathParamsOperationFilter>();
c.SchemaFilter<DtoSchemaFilter>();
c.CustomSchemaIds(type => type.ToString());
});
return services;
}
private static void SetAuthorization(this SwaggerGenOptions options, AuthorizationType authorizationType)
{
switch (authorizationType)
{
case AuthorizationType.None:
return;
case AuthorizationType.Basic:
options.AddSecurityDefinition("Basic",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = @"JWT Authorization header using the Basic scheme. Enter 'Basic' [space] and then your token in the text input below. Example: 'Basic 12345abcdef'",
Name = "Authorization",
Scheme = "Basic",
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Basic"
},
Scheme = "Basic",
Name = "Authorization",
In = ParameterLocation.Header
},
new List<string>()
}
});
break;
default:
throw new NotImplementedException($"Swagger extensions: Authorization type '{authorizationType}' is not implemented.");
}
}
public static IApplicationBuilder ConfigureSwagger(this IApplicationBuilder applicationBuilder, string endpointName)
{
applicationBuilder.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swagger, httpRequest) =>
{
var (host, basePath, scheme) = ReverseProxyHelper.GetUrlComponents(httpRequest);
swagger.Servers = new List<OpenApiServer>
{
new OpenApiServer {Url = $"{scheme}://{host}{basePath}"}
};
});
c.RouteTemplate = "swagger/{documentName}/swagger.json";
});
applicationBuilder.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", endpointName);
c.RoutePrefix = $"swagger";
});
return applicationBuilder;
}
}
}