< Summary

Information
Class: ArturRios.Util.WebApi.Configuration.WebApplicationBuilderExtensions
Assembly: ArturRios.Util.WebApi
File(s): /home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Configuration/WebApplicationBuilderExtensions.cs
Line coverage
52%
Covered lines: 26
Uncovered lines: 24
Coverable lines: 50
Total lines: 120
Line coverage: 52%
Branch coverage
50%
Covered branches: 6
Total branches: 12
Branch coverage: 50%
Method coverage
50%
Covered methods: 2
Fully covered methods: 0
Total methods: 4
Method coverage: 50%
Full method coverage: 0%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
LoadConfiguration(...)50%4480%
AddWebApiSwagger(...)0%620%
AddWebApiSwaggerWith(...)66.66%6693.33%
AddJwtSecurity(...)100%210%

File(s)

/home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Configuration/WebApplicationBuilderExtensions.cs

#LineLine coverage
 1using ArturRios.Configuration.Loaders;
 2using ArturRios.Configuration.Providers;
 3using Microsoft.AspNetCore.Authentication.JwtBearer;
 4using Microsoft.AspNetCore.Builder;
 5using Microsoft.Extensions.Configuration;
 6using Microsoft.Extensions.DependencyInjection;
 7using Microsoft.Extensions.DependencyInjection.Extensions;
 8using Microsoft.Extensions.Logging;
 9using Microsoft.OpenApi;
 10using Swashbuckle.AspNetCore.SwaggerGen;
 11
 12namespace ArturRios.Util.WebApi.Configuration;
 13
 14/// <summary>Builder-side steps of the standard web API setup. <see cref="WebApiStartup"/> runs them in order, and each
 15/// one can be used on its own with a plain <see cref="WebApplicationBuilder"/>.</summary>
 16public static class WebApplicationBuilderExtensions
 17{
 18    /// <param name="builder">The application builder.</param>
 19    extension(WebApplicationBuilder builder)
 20    {
 21        /// <summary>Loads <c>appsettings</c> and/or the environment file according to <paramref name="parameters"/>, an
 22        /// registers <paramref name="parameters"/>, the <see cref="ConfigurationLoader"/>, <see cref="SettingsProvider"
 23        /// (always, since <c>AuthenticationMiddleware</c> depends on it) and <see cref="EnvironmentProvider"/> (when th
 24        /// environment file is loaded) as services.</summary>
 25        /// <param name="parameters">The startup parameters deciding which sources are loaded.</param>
 26        /// <returns>The same <paramref name="builder"/> instance, for chaining.</returns>
 27        public WebApplicationBuilder LoadConfiguration(WebApiParameters parameters)
 28        {
 2029            ArgumentNullException.ThrowIfNull(parameters);
 30
 2031            var environmentName = builder.Environment.EnvironmentName;
 32
 2033            builder.Services.TryAddSingleton(parameters);
 2034            builder.Services.TryAddSingleton(sp => new ConfigurationLoader(builder.Configuration, environmentName, null,
 2035                sp.GetRequiredService<ILogger<ConfigurationLoader>>()));
 2036            builder.Services.TryAddSingleton<SettingsProvider>();
 37
 4038            using var loggerFactory = LoggerFactory.Create(logging => logging.AddConsole());
 39
 2040            var configurationLoader = new ConfigurationLoader(builder.Configuration, environmentName, null,
 2041                loggerFactory.CreateLogger<ConfigurationLoader>());
 42
 2043            if (parameters.UseAppSettings)
 44            {
 045                configurationLoader.LoadAppSettings();
 46            }
 47
 2048            if (parameters.UseEnvFile)
 49            {
 050                configurationLoader.LoadEnvironment();
 51
 052                builder.Services.TryAddSingleton<EnvironmentProvider>();
 53            }
 54
 2055            return builder;
 56        }
 57
 58        /// <summary>Registers the Swagger generator when Swagger is allowed in the current environment (see
 59        /// <see cref="WebApiParameters.IsSwaggerAllowed"/>), and marks it enabled under
 60        /// <see cref="AppSettingsKeys.SwaggerEnabled"/> so <c>AuthenticationMiddleware</c> lets <c>/swagger</c> through
 61        /// Pair it with <see cref="ApplicationBuilderExtensions.UseWebApiSwagger"/>, which serves whatever was register
 62        /// <param name="parameters">The startup parameters gating Swagger by environment.</param>
 63        /// <param name="configure">Optional callback to configure the allowed environments, JWT security and generator.
 64        /// <returns>The same <paramref name="builder"/> instance, for chaining.</returns>
 65        public WebApplicationBuilder AddWebApiSwagger(WebApiParameters parameters, Action<WebApiSwaggerOptions>? configu
 66        {
 067            var options = new WebApiSwaggerOptions();
 068            configure?.Invoke(options);
 69
 070            return builder.AddWebApiSwaggerWith(parameters, options);
 71        }
 72
 73        internal WebApplicationBuilder AddWebApiSwaggerWith(WebApiParameters parameters, WebApiSwaggerOptions options)
 74        {
 2075            ArgumentNullException.ThrowIfNull(parameters);
 76
 2077            if (!parameters.IsSwaggerAllowed(builder.Environment.EnvironmentName, options.AllowedEnvironments))
 78            {
 1679                return builder;
 80            }
 81
 482            builder.Configuration.AddInMemoryCollection(
 483                new Dictionary<string, string?> { [AppSettingsKeys.SwaggerEnabled] = "true" });
 84
 485            builder.Services.AddSwaggerGen(generator =>
 486            {
 387                options.ConfigureGenerator?.Invoke(generator);
 488
 389                if (options.JwtAuthentication)
 490                {
 091                    AddJwtSecurity(generator);
 492                }
 793            });
 94
 495            return builder;
 96        }
 97    }
 98
 99    private static void AddJwtSecurity(SwaggerGenOptions options)
 100    {
 0101        var jwtSecurityScheme = new OpenApiSecurityScheme
 0102        {
 0103            BearerFormat = "JWT",
 0104            Name = "JWT Authentication",
 0105            In = ParameterLocation.Header,
 0106            Type = SecuritySchemeType.Http,
 0107            Scheme = JwtBearerDefaults.AuthenticationScheme,
 0108            Description =
 0109                "After getting a token from the Authentication route, put **_ONLY_** your JWT Bearer token on textbox be
 0110        };
 111
 0112        var jwtRequirement = new OpenApiSecurityRequirement
 0113        {
 0114            { new OpenApiSecuritySchemeReference(JwtBearerDefaults.AuthenticationScheme), [] }
 0115        };
 116
 0117        options.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, jwtSecurityScheme);
 0118        options.AddSecurityRequirement(_ => jwtRequirement);
 0119    }
 120}