-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathSwaggerExtensions.cs
198 lines (178 loc) · 7.92 KB
/
SwaggerExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Kros.Swagger.Extensions
{
/// <summary>
/// Swagger service extensions.
/// </summary>
public static class SwaggerExtensions
{
private const string SwaggerDocumentationSectionName = "SwaggerDocumentation";
/// <summary>
/// Registers Swagger documentation generator to IoC container.
/// </summary>
/// <param name="services">IoC container.</param>
/// <param name="configuration">Application configuration.</param>
/// <param name="includeXmlcomments">
/// If <c>true</c>, includes XML comments from all <c>.xml</c> files in current domain base directory
/// (<see cref="SwaggerGenOptionsExtensions.IncludeXmlCommentsFromAllFilesInCurrentDomainBaseDirectory(SwaggerGenOptions)"/>).
/// </param>
/// <param name="setupAction">Action for configuring swagger generating options.</param>
public static IServiceCollection AddSwaggerDocumentation(
this IServiceCollection services,
IConfiguration configuration,
bool includeXmlcomments,
Action<SwaggerGenOptions>? setupAction = null)
{
SwaggerSettings? settings = configuration.GetSwaggerSettings();
services.ConfigureSwaggerGen(options =>
{
// '+' (nested classes) is not valid character in OpenApi reference.
options.CustomSchemaIds(x => x.FullName?.Replace("+", "-"));
});
services.AddSwaggerGen(c =>
{
if (settings is not null)
{
c.SwaggerDoc(settings.Version, settings);
AddAuthorization(c, settings);
}
if (includeXmlcomments)
{
c.IncludeXmlCommentsFromAllFilesInCurrentDomainBaseDirectory();
}
c.UseClassNameAsTitle();
c.UseNullableSchemaFilter();
setupAction?.Invoke(c);
});
return services;
}
/// <summary>
/// Registers Swagger documentation generator to IoC container. Does not add XML documentation files.
/// </summary>
/// <param name="services">IoC container.</param>
/// <param name="configuration">Application configuration.</param>
/// <param name="setupAction">Action for configuring swagger generating options.</param>
public static IServiceCollection AddSwaggerDocumentation(
this IServiceCollection services,
IConfiguration configuration,
Action<SwaggerGenOptions>? setupAction = null)
=> AddSwaggerDocumentation(services, configuration, false, setupAction);
/// <summary>
/// Adds Swagger documentation generator middleware.
/// </summary>
/// <param name="app">Application.</param>
/// <param name="configuration">Application configuration.</param>
/// <param name="setupAction">Action for configuring swagger options.</param>
/// <param name="setupUiAction">Action for configuring swagger UI options.</param>
public static IApplicationBuilder UseSwaggerDocumentation(
this IApplicationBuilder app,
IConfiguration configuration,
Action<SwaggerOptions>? setupAction = null,
Action<SwaggerUIOptions>? setupUiAction = null)
{
SwaggerSettings? settings = configuration.GetSwaggerSettings();
app.UseSwagger(c =>
{
setupAction?.Invoke(c);
})
.UseSwaggerUI(c =>
{
if (settings is not null)
{
c.SwaggerEndpoint($"{settings.Version}/swagger.json", settings.Title);
c.OAuthClientId(settings.OAuthClientId);
c.OAuthClientSecret(settings.OAuthClientSecret);
c.OAuthScopes(GetAllOAuthScopes(settings.Authorizations.Values));
c.OAuthUsePkce();
}
setupUiAction?.Invoke(c);
});
return app;
}
internal static SwaggerSettings? GetSwaggerSettings(this IConfiguration configuration)
{
IConfigurationSection configurationSection = configuration.GetSection(SwaggerDocumentationSectionName);
return configurationSection.Exists() ? configurationSection.Get<SwaggerSettings>() : null;
}
private static void AddAuthorization(SwaggerGenOptions swaggerOptions, SwaggerSettings settings)
{
foreach (KeyValuePair<string, OpenApiSecurityScheme> auth in settings.Authorizations)
{
string name = auth.Key;
OpenApiSecurityScheme scheme = auth.Value;
swaggerOptions.AddSecurityDefinition(name, scheme);
}
}
internal static IList<OpenApiSecurityRequirement> CreateSecurityRequirements(this SwaggerSettings settings)
{
return settings.Authorizations.Select(item =>
{
OpenApiSecurityScheme scheme = item.Value;
string schemeName = item.Key;
// From OpenApiSecurityRequirement documentation:
// If the security scheme is of type "oauth2" or "openIdConnect",
// then the scopes value is a list of scope names required for the execution.
// For other security scheme types, the array MUST be empty
List<string> scopes = [];
if (((scheme.Type == SecuritySchemeType.OAuth2) || (scheme.Type == SecuritySchemeType.OpenIdConnect))
&& (scheme.Flows is not null))
{
scheme.GetScopes(scopes);
scopes = scopes.Distinct(StringComparer.Ordinal).ToList();
}
OpenApiSecurityRequirement req = new()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = schemeName
}
},
scopes
}
};
return req;
}).ToList();
}
private static string[] GetAllOAuthScopes(IEnumerable<OpenApiSecurityScheme> schemes)
{
List<string> allScopes = [];
foreach (OpenApiSecurityScheme scheme in schemes)
{
scheme.GetScopes(allScopes);
}
return allScopes.Distinct(StringComparer.Ordinal).ToArray();
}
internal static void GetScopes(this OpenApiSecurityScheme scheme, List<string> scopes)
{
static void AddFlowScopes(List<string> scopes, OpenApiOAuthFlow? flow)
{
IEnumerable<string>? flowScopes = flow?.Scopes?.Keys;
if (flowScopes is not null)
{
scopes.AddRange(flowScopes);
}
}
if (((scheme.Type == SecuritySchemeType.OAuth2) || (scheme.Type == SecuritySchemeType.OpenIdConnect))
&& (scheme.Flows is not null))
{
AddFlowScopes(scopes, scheme.Flows.Implicit);
AddFlowScopes(scopes, scheme.Flows.Password);
AddFlowScopes(scopes, scheme.Flows.ClientCredentials);
AddFlowScopes(scopes, scheme.Flows.AuthorizationCode);
}
}
}
}