| | | 1 | | using ArturRios.Configuration.Enums; |
| | | 2 | | using ArturRios.Configuration.Loaders; |
| | | 3 | | using ArturRios.Configuration.Providers; |
| | | 4 | | using ArturRios.Extensions; |
| | | 5 | | using ArturRios.Output; |
| | | 6 | | using ArturRios.Util.WebApi.Middleware; |
| | | 7 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | | 8 | | using Microsoft.AspNetCore.Builder; |
| | | 9 | | using Microsoft.AspNetCore.Mvc; |
| | | 10 | | using Microsoft.Extensions.Configuration; |
| | | 11 | | using Microsoft.Extensions.DependencyInjection; |
| | | 12 | | using Microsoft.Extensions.Logging; |
| | | 13 | | using Microsoft.OpenApi; |
| | | 14 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | | 15 | | |
| | | 16 | | namespace ArturRios.Util.WebApi.Configuration; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Base class for bootstrapping an ASP.NET Core web API: builds the <see cref="WebApplicationBuilder"/> and |
| | | 20 | | /// <see cref="WebApplication"/>, wires up configuration, middlewares and Swagger, and exposes hooks |
| | | 21 | | /// (<see cref="Build"/>, <see cref="ConfigureApp"/>, <see cref="AddDependencies"/>, etc.) for derived classes |
| | | 22 | | /// to customize the pipeline. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="args">The command-line arguments passed to the application entry point.</param> |
| | 0 | 25 | | public abstract class WebApiStartup(string[] args) |
| | | 26 | | { |
| | 0 | 27 | | private readonly Action<SwaggerGenOptions> _swaggerGenJwtAuthentication = setup => |
| | 0 | 28 | | { |
| | 0 | 29 | | var jwtSecurityScheme = new OpenApiSecurityScheme |
| | 0 | 30 | | { |
| | 0 | 31 | | BearerFormat = "JWT", |
| | 0 | 32 | | Name = "JWT Authentication", |
| | 0 | 33 | | In = ParameterLocation.Header, |
| | 0 | 34 | | Type = SecuritySchemeType.Http, |
| | 0 | 35 | | Scheme = JwtBearerDefaults.AuthenticationScheme, |
| | 0 | 36 | | Description = |
| | 0 | 37 | | "After getting a token from the Authentication route, put **_ONLY_** your JWT Bearer token on textbox be |
| | 0 | 38 | | }; |
| | 0 | 39 | | |
| | 0 | 40 | | var jwtRequirement = new OpenApiSecurityRequirement |
| | 0 | 41 | | { |
| | 0 | 42 | | { new OpenApiSecuritySchemeReference(JwtBearerDefaults.AuthenticationScheme), [] } |
| | 0 | 43 | | }; |
| | 0 | 44 | | |
| | 0 | 45 | | setup.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, jwtSecurityScheme); |
| | 0 | 46 | | setup.AddSecurityRequirement(_ => jwtRequirement); |
| | 0 | 47 | | }; |
| | | 48 | | |
| | | 49 | | /// <summary>The builder used to configure services before the application is built.</summary> |
| | 0 | 50 | | protected readonly WebApplicationBuilder Builder = WebApplication.CreateBuilder(args); |
| | | 51 | | |
| | | 52 | | /// <summary>The startup parameters parsed from the command-line arguments.</summary> |
| | 0 | 53 | | protected readonly WebApiParameters Parameters = new(args); |
| | | 54 | | |
| | 0 | 55 | | private SettingsProvider _settings = null!; |
| | | 56 | | |
| | | 57 | | /// <summary>The built application. Populated by <see cref="BuildApp"/>.</summary> |
| | 0 | 58 | | protected WebApplication App = null!; |
| | | 59 | | |
| | | 60 | | /// <summary>Performs the full startup sequence (configuration, services, middlewares, etc.). Implemented by derived |
| | | 61 | | public abstract void Build(); |
| | | 62 | | |
| | | 63 | | /// <summary>Runs the built application, blocking until it shuts down.</summary> |
| | 0 | 64 | | public void Run() => App.Run(); |
| | | 65 | | |
| | | 66 | | /// <summary>Calls <see cref="Build"/> followed by <see cref="Run"/>.</summary> |
| | | 67 | | public void BuildAndRun() |
| | 0 | 68 | | { |
| | 0 | 69 | | Build(); |
| | 0 | 70 | | Run(); |
| | 0 | 71 | | } |
| | | 72 | | |
| | | 73 | | /// <summary>Builds <see cref="App"/> from <see cref="Builder"/>.</summary> |
| | 0 | 74 | | public void BuildApp() => App = Builder.Build(); |
| | | 75 | | |
| | | 76 | | /// <summary>Configures the built application's request pipeline. Implemented by derived classes.</summary> |
| | | 77 | | public abstract void ConfigureApp(); |
| | | 78 | | |
| | | 79 | | /// <summary>Registers application-specific dependencies. Override to add custom services.</summary> |
| | 0 | 80 | | public virtual void AddDependencies() { } |
| | | 81 | | |
| | | 82 | | /// <summary>Configures CORS policies. Override to enable and customize CORS.</summary> |
| | 0 | 83 | | public virtual void ConfigureCors() { } |
| | | 84 | | |
| | | 85 | | /// <summary>Configures authentication/authorization. Override to enable custom security.</summary> |
| | 0 | 86 | | public virtual void ConfigureSecurity() { } |
| | | 87 | | |
| | | 88 | | /// <summary>Configures web API-specific services (controllers, filters, etc.). Override to customize.</summary> |
| | 0 | 89 | | public virtual void ConfigureWebApi() { } |
| | | 90 | | |
| | | 91 | | /// <summary>Starts background or hosted services. Override to start custom services.</summary> |
| | 0 | 92 | | public virtual void StartServices() { } |
| | | 93 | | |
| | | 94 | | /// <summary>Loads application settings and/or the environment file according to <see cref="Parameters"/>, |
| | | 95 | | /// and registers the resulting <see cref="SettingsProvider"/>/<see cref="EnvironmentProvider"/> as services.</summa |
| | | 96 | | public void LoadConfiguration() |
| | 0 | 97 | | { |
| | 0 | 98 | | Builder.Services.AddSingleton(sp => |
| | 0 | 99 | | new ConfigurationLoader(Builder.Configuration, Builder.Environment.EnvironmentName, |
| | 0 | 100 | | null, sp.GetRequiredService<ILogger<ConfigurationLoader>>())); |
| | | 101 | | |
| | 0 | 102 | | using var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); |
| | 0 | 103 | | var configurationLoader = new ConfigurationLoader( |
| | 0 | 104 | | Builder.Configuration, Builder.Environment.EnvironmentName, null, |
| | 0 | 105 | | loggerFactory.CreateLogger<ConfigurationLoader>()); |
| | | 106 | | |
| | 0 | 107 | | SetSwaggerConfigFromParameters(); |
| | | 108 | | |
| | 0 | 109 | | _settings = new SettingsProvider(Builder.Configuration); |
| | | 110 | | |
| | 0 | 111 | | if (Parameters.UseAppSettings) |
| | 0 | 112 | | { |
| | 0 | 113 | | configurationLoader.LoadAppSettings(); |
| | | 114 | | |
| | 0 | 115 | | Builder.Services.AddSingleton<SettingsProvider>(); |
| | 0 | 116 | | } |
| | | 117 | | |
| | 0 | 118 | | if (Parameters.UseEnvFile) |
| | 0 | 119 | | { |
| | 0 | 120 | | configurationLoader.LoadEnvironment(); |
| | | 121 | | |
| | 0 | 122 | | Builder.Services.AddSingleton<EnvironmentProvider>(); |
| | 0 | 123 | | } |
| | 0 | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary>Registers each given middleware type on the application pipeline, skipping any type that does |
| | | 127 | | /// not derive from <see cref="WebApiMiddleware"/>.</summary> |
| | | 128 | | /// <param name="middlewares">The middleware types to register, in pipeline order.</param> |
| | | 129 | | public void AddMiddlewares(Type[] middlewares) |
| | 0 | 130 | | { |
| | 0 | 131 | | foreach (var middleware in middlewares) |
| | 0 | 132 | | { |
| | 0 | 133 | | if (middleware.IsSubclassOf(typeof(WebApiMiddleware))) |
| | 0 | 134 | | { |
| | 0 | 135 | | App.UseMiddleware(middleware); |
| | 0 | 136 | | } |
| | 0 | 137 | | } |
| | 0 | 138 | | } |
| | | 139 | | |
| | | 140 | | /// <summary>Replaces ASP.NET Core's default invalid-model-state response with a 400 result carrying a |
| | | 141 | | /// <see cref="DataOutput{T}"/> whose errors list each invalid parameter and its message.</summary> |
| | | 142 | | public void AddCustomInvalidModelStateResponse() => |
| | 0 | 143 | | Builder.Services.Configure<ApiBehaviorOptions>(options => |
| | 0 | 144 | | { |
| | 0 | 145 | | options.InvalidModelStateResponseFactory = context => |
| | 0 | 146 | | { |
| | 0 | 147 | | var errors = context.ModelState |
| | 0 | 148 | | .Where(e => e.Value?.Errors.Count > 0) |
| | 0 | 149 | | .Select(e => $"Parameter: {e.Key} | Error: {e.Value?.Errors.First().ErrorMessage}").ToArray(); |
| | 0 | 150 | | |
| | 0 | 151 | | var output = DataOutput<string>.New |
| | 0 | 152 | | .WithData(string.Empty) |
| | 0 | 153 | | .WithErrors(errors); |
| | 0 | 154 | | |
| | 0 | 155 | | return new BadRequestObjectResult(output); |
| | 0 | 156 | | }; |
| | 0 | 157 | | }); |
| | | 158 | | |
| | | 159 | | /// <summary>Enables the Swagger middleware (JSON endpoint and UI) when the current environment is allowed, |
| | | 160 | | /// as determined by <paramref name="allowedEnvironments"/>, <see cref="WebApiParameters.GetSwaggerEnvironments"/>, |
| | | 161 | | /// or <see cref="AppSettingsKeys.SwaggerEnabled"/>, in that order of precedence.</summary> |
| | | 162 | | /// <param name="allowedEnvironments">Optional explicit list of environments in which Swagger should be served.</par |
| | | 163 | | public void UseSwagger(EnvironmentType[]? allowedEnvironments = null) |
| | 0 | 164 | | { |
| | | 165 | | bool useSwagger; |
| | 0 | 166 | | var currentEnv = Builder.Environment.EnvironmentName; |
| | 0 | 167 | | var swaggerEnvs = Parameters.GetSwaggerEnvironments(); |
| | | 168 | | |
| | 0 | 169 | | if (allowedEnvironments.IsNotEmpty()) |
| | 0 | 170 | | { |
| | 0 | 171 | | useSwagger = allowedEnvironments!.Any(env => |
| | 0 | 172 | | env.ToString().Equals(currentEnv, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 173 | | } |
| | 0 | 174 | | else if (swaggerEnvs.IsNotEmpty()) |
| | 0 | 175 | | { |
| | 0 | 176 | | useSwagger = swaggerEnvs.Contains(currentEnv, StringComparer.OrdinalIgnoreCase); |
| | 0 | 177 | | } |
| | | 178 | | else |
| | 0 | 179 | | { |
| | 0 | 180 | | useSwagger = _settings.GetBool(AppSettingsKeys.SwaggerEnabled) ?? false; |
| | 0 | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | if (!useSwagger) |
| | 0 | 184 | | { |
| | 0 | 185 | | return; |
| | | 186 | | } |
| | | 187 | | |
| | 0 | 188 | | App.UseSwagger(); |
| | 0 | 189 | | App.UseSwaggerUI(); |
| | 0 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary>Registers the Swagger generator (<c>AddSwaggerGen</c>) when the current environment is allowed, |
| | | 193 | | /// optionally applying custom <see cref="SwaggerGenOptions"/> and/or JWT bearer security definitions.</summary> |
| | | 194 | | /// <param name="allowedEnvironments">Optional explicit list of environments in which Swagger docs should be generat |
| | | 195 | | /// <param name="swaggerGenOptions">Optional callback to further configure <see cref="SwaggerGenOptions"/>.</param> |
| | | 196 | | /// <param name="jwtAuthentication">Whether to add a JWT bearer security definition/requirement to the generated doc |
| | | 197 | | public void UseSwaggerGen(EnvironmentType[]? allowedEnvironments = null, |
| | | 198 | | Action<SwaggerGenOptions>? swaggerGenOptions = null, bool jwtAuthentication = false) |
| | 0 | 199 | | { |
| | 0 | 200 | | var useSwaggerDocs = false; |
| | 0 | 201 | | var currentEnv = Builder.Environment.EnvironmentName; |
| | 0 | 202 | | var swaggerEnvs = Parameters.GetSwaggerEnvironments(); |
| | | 203 | | |
| | 0 | 204 | | if (allowedEnvironments.IsNotEmpty()) |
| | 0 | 205 | | { |
| | 0 | 206 | | useSwaggerDocs = allowedEnvironments!.Any(env => |
| | 0 | 207 | | env.ToString().Equals(currentEnv, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 208 | | } |
| | 0 | 209 | | else if (swaggerEnvs.IsNotEmpty()) |
| | 0 | 210 | | { |
| | 0 | 211 | | useSwaggerDocs = swaggerEnvs.Contains(currentEnv, StringComparer.OrdinalIgnoreCase); |
| | 0 | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | if (!useSwaggerDocs) |
| | 0 | 215 | | { |
| | 0 | 216 | | return; |
| | | 217 | | } |
| | | 218 | | |
| | 0 | 219 | | Builder.Services.AddSwaggerGen(options => |
| | 0 | 220 | | { |
| | 0 | 221 | | swaggerGenOptions?.Invoke(options); |
| | 0 | 222 | | |
| | 0 | 223 | | if (jwtAuthentication) |
| | 0 | 224 | | { |
| | 0 | 225 | | _swaggerGenJwtAuthentication.Invoke(options); |
| | 0 | 226 | | } |
| | 0 | 227 | | }); |
| | 0 | 228 | | } |
| | | 229 | | |
| | | 230 | | private void SetSwaggerConfigFromParameters() |
| | 0 | 231 | | { |
| | 0 | 232 | | var currentEnv = Builder.Environment.EnvironmentName; |
| | | 233 | | |
| | 0 | 234 | | if (!Parameters.SwaggerEnvironments.Contains(currentEnv, StringComparer.OrdinalIgnoreCase)) |
| | 0 | 235 | | { |
| | 0 | 236 | | return; |
| | | 237 | | } |
| | | 238 | | |
| | 0 | 239 | | var configValues = new Dictionary<string, string?> { [AppSettingsKeys.SwaggerEnabled] = "true" }; |
| | | 240 | | |
| | 0 | 241 | | Builder.Configuration.AddInMemoryCollection(configValues); |
| | 0 | 242 | | } |
| | | 243 | | } |