From 3491e4462b3c40b41eaff5ae194285bad8d4d54a Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 21:51:34 +0800 Subject: [PATCH 01/21] refactor: rename JwtTokenService => JsonWebTokenService --- .../Jwt/DependencyInjectionExtensions.cs | 2 +- .../Authorization/Jwt/JwtTokenService.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs index dce2828..e198031 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs @@ -15,7 +15,7 @@ public static IServiceCollection AddJwtTokenService(this IServiceCollection serv Guard.NotNull(serviceCollection); Guard.NotNull(optionsAction); serviceCollection.Configure(optionsAction); - serviceCollection.TryAddSingleton(); + serviceCollection.TryAddSingleton(); serviceCollection.ConfigureOptions(); return serviceCollection; } diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs index 50ba755..2827dc0 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs @@ -10,7 +10,7 @@ namespace WeihanLi.Web.Authorization.Jwt; -public class JwtTokenService : ITokenService +public class JsonWebTokenService : ITokenService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly JwtSecurityTokenHandler _tokenHandler = new(); @@ -20,7 +20,7 @@ private readonly Lazy _lazyTokenValidationParameters, _lazyRefreshTokenValidationParameters; - public JwtTokenService(IHttpContextAccessor httpContextAccessor, IOptions tokenOptions) + public JsonWebTokenService(IHttpContextAccessor httpContextAccessor, IOptions tokenOptions) { _httpContextAccessor = httpContextAccessor; _tokenOptions = tokenOptions.Value; @@ -60,7 +60,7 @@ public virtual async Task RefreshToken(string refreshToken) protected virtual Task GetRefreshToken(Claim[] claims, string jti) { - var claimList = new List((claims ?? Array.Empty()) + var claimList = new List((claims ?? []) .Where(c => c.Type != _tokenOptions.RefreshTokenOwnerClaimType) .Union(new[] { new Claim(_tokenOptions.RefreshTokenOwnerClaimType, jti) }) ); @@ -83,14 +83,14 @@ protected virtual Task GetRefreshToken(Claim[] claims, string jti) return encodedJwt.WrapTask(); } - private static readonly HashSet JwtInternalClaimTypes = new() - { + private static readonly HashSet JwtInternalClaimTypes = + [ "iss", "exp", "aud", "nbf", "iat" - }; + ]; private async Task GenerateTokenInternal(bool refreshToken, Claim[] claims) { From 22a3a9aa74d8f0bbe402f0039839d5ddf5f33f63 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 21:55:17 +0800 Subject: [PATCH 02/21] refactor: more rename on JwtToken => JsonWebToken --- samples/WeihanLi.Web.Extensions.Samples/Program.cs | 2 +- .../Authorization/Jwt/DependencyInjectionExtensions.cs | 8 ++++---- .../Jwt/{JwtTokenOptions.cs => JsonWebTokenOptions.cs} | 2 +- ...wtTokenOptionsSetup.cs => JsonWebTokenOptionsSetup.cs} | 8 ++++---- .../Jwt/{JwtTokenService.cs => JsonWebTokenService.cs} | 4 ++-- .../Authorization/Jwt/JwtBearerOptionsPostSetup.cs | 4 ++-- 6 files changed, 14 insertions(+), 14 deletions(-) rename src/WeihanLi.Web.Extensions/Authorization/Jwt/{JwtTokenOptions.cs => JsonWebTokenOptions.cs} (99%) rename src/WeihanLi.Web.Extensions/Authorization/Jwt/{JwtTokenOptionsSetup.cs => JsonWebTokenOptionsSetup.cs} (76%) rename src/WeihanLi.Web.Extensions/Authorization/Jwt/{JwtTokenService.cs => JsonWebTokenService.cs} (98%) diff --git a/samples/WeihanLi.Web.Extensions.Samples/Program.cs b/samples/WeihanLi.Web.Extensions.Samples/Program.cs index db96781..849bc0c 100644 --- a/samples/WeihanLi.Web.Extensions.Samples/Program.cs +++ b/samples/WeihanLi.Web.Extensions.Samples/Program.cs @@ -41,7 +41,7 @@ options.KeyLocation = KeyLocation.HeaderOrQuery; }) ; -builder.Services.AddJwtTokenServiceWithJwtBearerAuth(options => +builder.Services.AddJsonWebTokenServiceWithJwtBearerAuth(options => { options.SecretKey = Guid.NewGuid().ToString(); options.Issuer = "https://id.weihanli.xyz"; diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs index e198031..4c944bb 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs @@ -10,17 +10,17 @@ namespace WeihanLi.Web.Authorization.Jwt; public static class DependencyInjectionExtensions { - public static IServiceCollection AddJwtTokenService(this IServiceCollection serviceCollection, Action optionsAction) + public static IServiceCollection AddJsonWebTokenService(this IServiceCollection serviceCollection, Action optionsAction) { Guard.NotNull(serviceCollection); Guard.NotNull(optionsAction); serviceCollection.Configure(optionsAction); serviceCollection.TryAddSingleton(); - serviceCollection.ConfigureOptions(); + serviceCollection.ConfigureOptions(); return serviceCollection; } - public static IServiceCollection AddJwtTokenServiceWithJwtBearerAuth(this IServiceCollection serviceCollection, Action optionsAction, Action jwtBearerOptionsSetup = null) + public static IServiceCollection AddJsonWebTokenServiceWithJwtBearerAuth(this IServiceCollection serviceCollection, Action optionsAction, Action jwtBearerOptionsSetup = null) { Guard.NotNull(serviceCollection); Guard.NotNull(optionsAction); @@ -29,6 +29,6 @@ public static IServiceCollection AddJwtTokenServiceWithJwtBearerAuth(this IServi serviceCollection.Configure(jwtBearerOptionsSetup); } serviceCollection.ConfigureOptions(); - return serviceCollection.AddJwtTokenService(optionsAction); + return serviceCollection.AddJsonWebTokenService(optionsAction); } } diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptions.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptions.cs similarity index 99% rename from src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptions.cs rename to src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptions.cs index 2054e6d..efc2b96 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptions.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptions.cs @@ -6,7 +6,7 @@ namespace WeihanLi.Web.Authorization.Jwt; -public sealed class JwtTokenOptions +public sealed class JsonWebTokenOptions { /// /// "iss" (Issuer) Claim diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptionsSetup.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs similarity index 76% rename from src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptionsSetup.cs rename to src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs index 3e3b08e..c051a4f 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenOptionsSetup.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs @@ -7,9 +7,9 @@ namespace WeihanLi.Web.Authorization.Jwt; -internal sealed class JwtTokenOptionsSetup : IPostConfigureOptions +internal sealed class JsonWebTokenOptionsSetup : IPostConfigureOptions { - public void PostConfigure(string name, JwtTokenOptions options) + public void PostConfigure(string name, JsonWebTokenOptions options) { if (options.SigningCredentialsFactory is null) { @@ -18,8 +18,8 @@ public void PostConfigure(string name, JwtTokenOptions options) options.SigningCredentialsFactory = () => new SigningCredentials(new SymmetricSecurityKey(options.SecretKey.GetBytes()), SecurityAlgorithms.HmacSha256); } } - Guard.NotNull(options.SigningCredentialsFactory); - options.SigningCredentials = options.SigningCredentialsFactory(); + ArgumentNullException.ThrowIfNull(options.SigningCredentialsFactory); + options.SigningCredentials = options.SigningCredentialsFactory.Invoke(); options.RefreshTokenSigningCredentials = options.RefreshTokenSigningCredentials is null ? options.SigningCredentials : options.RefreshTokenSigningCredentialsFactory() diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenService.cs similarity index 98% rename from src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs rename to src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenService.cs index 2827dc0..6f89722 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtTokenService.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenService.cs @@ -14,13 +14,13 @@ public class JsonWebTokenService : ITokenService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly JwtSecurityTokenHandler _tokenHandler = new(); - private readonly JwtTokenOptions _tokenOptions; + private readonly JsonWebTokenOptions _tokenOptions; private readonly Lazy _lazyTokenValidationParameters, _lazyRefreshTokenValidationParameters; - public JsonWebTokenService(IHttpContextAccessor httpContextAccessor, IOptions tokenOptions) + public JsonWebTokenService(IHttpContextAccessor httpContextAccessor, IOptions tokenOptions) { _httpContextAccessor = httpContextAccessor; _tokenOptions = tokenOptions.Value; diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtBearerOptionsPostSetup.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtBearerOptionsPostSetup.cs index 3733faa..5294665 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtBearerOptionsPostSetup.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JwtBearerOptionsPostSetup.cs @@ -8,9 +8,9 @@ namespace WeihanLi.Web.Authorization.Jwt; internal sealed class JwtBearerOptionsPostSetup : IPostConfigureOptions { - private readonly IOptions _options; + private readonly IOptions _options; - public JwtBearerOptionsPostSetup(IOptions options) + public JwtBearerOptionsPostSetup(IOptions options) { _options = options; } From b0e9662c0019304f3f065eb7e7202377df84871c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sun, 23 Jun 2024 13:56:06 +0000 Subject: [PATCH 03/21] Automated dotnet-format update from commit 22a3a9aa74d8f0bbe402f0039839d5ddf5f33f63 on refs/heads/dev --- .../Authorization/Jwt/JsonWebTokenOptionsSetup.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs index c051a4f..eaf381b 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/JsonWebTokenOptionsSetup.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using Microsoft.IdentityModel.Tokens; -using WeihanLi.Common; using WeihanLi.Extensions; namespace WeihanLi.Web.Authorization.Jwt; From 8bbfc94c0b2de493c603cd2c3816b947d930187b Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 21:57:11 +0800 Subject: [PATCH 04/21] update package version --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 9674e88..3b034a5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ 1 - 10 + 11 0 $(VersionMajor).$(VersionMinor).$(VersionPatch) develop From 47d7834b4c620cd0d0be36c0bceb049cb4dc6fe9 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 21:57:54 +0800 Subject: [PATCH 05/21] build: remove build.cake --- build.cake | 165 ----------------------------------------------------- 1 file changed, 165 deletions(-) delete mode 100644 build.cake diff --git a/build.cake b/build.cake deleted file mode 100644 index 44b4bc3..0000000 --- a/build.cake +++ /dev/null @@ -1,165 +0,0 @@ -using System.Collections.Generic; -/////////////////////////////////////////////////////////////////////////////// -// ARGUMENTS -/////////////////////////////////////////////////////////////////////////////// - -var apiKey = Argument("apiKey", ""); -var stable = Argument("stable", "false"); -var target = Argument("target", "Default"); -var configuration = Argument("configuration", "Release"); - -var solutionPath = "./WeihanLi.Web.Extensions.sln"; -var srcProjects = GetFiles("./src/**/*.csproj"); -var packProjects = GetFiles("./src/**/*.csproj"); -var testProjects = GetFiles("./test/**/*.csproj"); - -var artifacts = "./artifacts/packages"; -var isWindowsAgent = (EnvironmentVariable("Agent_OS") ?? "Windows_NT") == "Windows_NT"; -var branchName = EnvironmentVariable("BUILD_SOURCEBRANCHNAME") ?? "local"; - -/////////////////////////////////////////////////////////////////////////////// -// SETUP / TEARDOWN -/////////////////////////////////////////////////////////////////////////////// - -Setup(ctx => -{ - // Executed BEFORE the first task. - Information("Running tasks..."); - PrintBuildInfo(); -}); - -Teardown(ctx => -{ - // Executed AFTER the last task. - Information("Finished running tasks."); -}); - -/////////////////////////////////////////////////////////////////////////////// -// TASKS -/////////////////////////////////////////////////////////////////////////////// - -Task("clean") - .Description("Clean") - .Does(() => - { - var deleteSetting = new DeleteDirectorySettings() - { - Force = true, - Recursive = true - }; - if (DirectoryExists(artifacts)) - { - DeleteDirectory(artifacts, deleteSetting); - } - }); - -Task("restore") - .Description("Restore") - .Does(() => - { - foreach(var project in srcProjects) - { - DotNetRestore(project.FullPath); - } - }); - -Task("build") - .Description("Build") - .IsDependentOn("clean") - .IsDependentOn("restore") - .Does(() => - { - var buildSetting = new DotNetBuildSettings{ - NoRestore = true, - Configuration = configuration - }; - foreach(var project in srcProjects) - { - DotNetBuild(project.FullPath, buildSetting); - } - }); - -Task("test") - .Description("Test") - .IsDependentOn("build") - .Does(() => - { - var testSettings = new DotNetTestSettings{ - NoRestore = true, - Configuration = configuration - }; - foreach(var project in testProjects) - { - DotNetTest(project.FullPath, testSettings); - } - }); - -Task("pack") - .Description("Pack package") - .IsDependentOn("build") - .Does((context) => - { - var settings = new DotNetPackSettings - { - Configuration = configuration, - OutputDirectory = artifacts, - VersionSuffix = "", - NoRestore = true, - NoBuild = true - }; - if(branchName != "master" && stable != "true"){ - settings.VersionSuffix = $"preview-{DateTime.UtcNow:yyyyMMdd-HHmmss}"; - } - foreach (var project in packProjects) - { - DotNetPack(project.FullPath, settings); - } - PublishArtifacts(context); - }); - -bool PublishArtifacts(ICakeContext context) -{ - if (context.Environment.Platform.IsUnix()) - { - return false; - } - var publishBranches = new HashSet() - { - "local", - "main", - "master", - "preview" - }; - - if (string.IsNullOrEmpty(apiKey) && publishBranches.Contains(branchName)) - { - apiKey = EnvironmentVariable("Nuget__ApiKey"); - } - if (!string.IsNullOrEmpty(apiKey)) - { - var pushSetting = new DotNetNuGetPushSettings - { - Source = "https://api.nuget.org/v3/index.json", - ApiKey = apiKey, - SkipDuplicate = true - }; - var packages = GetFiles($"{artifacts}/*.nupkg"); - foreach (var package in packages) - { - DotNetNuGetPush(package.FullPath, pushSetting); - } - return true; - } - return false; -} - -void PrintBuildInfo(){ - Information($@"branch:{branchName}, agentOs={EnvironmentVariable("Agent_OS")} - BuildID:{EnvironmentVariable("BUILD_BUILDID")},BuildNumber:{EnvironmentVariable("BUILD_BUILDNUMBER")},BuildReason:{EnvironmentVariable("BUILD_REASON")} - "); -} - -Task("Default") - .IsDependentOn("pack"); - -RunTarget(target); \ No newline at end of file From 59f7b2d8f482df627d199b6cd0cbb405d110276a Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 22:04:18 +0800 Subject: [PATCH 06/21] feat: enable central package version management --- Directory.Packages.props | 21 +++++++++++++++++++ .../WeihanLi.Web.Extensions.Samples.csproj | 4 ++-- .../WeihanLi.Web.Extensions.csproj | 9 +++----- .../WeihanLi.Web.Extensions.UnitTest.csproj | 8 +++---- 4 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 Directory.Packages.props diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..98ef3f9 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,21 @@ + + + true + true + + + + + + + + + + + + + + + + + diff --git a/samples/WeihanLi.Web.Extensions.Samples/WeihanLi.Web.Extensions.Samples.csproj b/samples/WeihanLi.Web.Extensions.Samples/WeihanLi.Web.Extensions.Samples.csproj index 27e092f..36a1de4 100644 --- a/samples/WeihanLi.Web.Extensions.Samples/WeihanLi.Web.Extensions.Samples.csproj +++ b/samples/WeihanLi.Web.Extensions.Samples/WeihanLi.Web.Extensions.Samples.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -11,6 +11,6 @@ - + \ No newline at end of file diff --git a/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj b/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj index 99c05c8..6f04eb3 100644 --- a/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj +++ b/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj @@ -10,12 +10,9 @@ WeihanLi.Web - - - - - - + + + diff --git a/test/WeihanLi.Web.Extensions.UnitTest/WeihanLi.Web.Extensions.UnitTest.csproj b/test/WeihanLi.Web.Extensions.UnitTest/WeihanLi.Web.Extensions.UnitTest.csproj index bb6a085..0b69daa 100644 --- a/test/WeihanLi.Web.Extensions.UnitTest/WeihanLi.Web.Extensions.UnitTest.csproj +++ b/test/WeihanLi.Web.Extensions.UnitTest/WeihanLi.Web.Extensions.UnitTest.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -7,9 +7,9 @@ - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all From 6fa2899fabbe67066ee7393abe504569f5dd505f Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 23 Jun 2024 22:07:43 +0800 Subject: [PATCH 07/21] refactor: rename extensions JsonWebTokenService => JwtService --- samples/WeihanLi.Web.Extensions.Samples/Program.cs | 2 +- .../Authorization/Jwt/DependencyInjectionExtensions.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/WeihanLi.Web.Extensions.Samples/Program.cs b/samples/WeihanLi.Web.Extensions.Samples/Program.cs index 849bc0c..7282ab3 100644 --- a/samples/WeihanLi.Web.Extensions.Samples/Program.cs +++ b/samples/WeihanLi.Web.Extensions.Samples/Program.cs @@ -41,7 +41,7 @@ options.KeyLocation = KeyLocation.HeaderOrQuery; }) ; -builder.Services.AddJsonWebTokenServiceWithJwtBearerAuth(options => +builder.Services.AddJwtServiceWithJwtBearerAuth(options => { options.SecretKey = Guid.NewGuid().ToString(); options.Issuer = "https://id.weihanli.xyz"; diff --git a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs index 4c944bb..f76e003 100644 --- a/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Authorization/Jwt/DependencyInjectionExtensions.cs @@ -10,7 +10,7 @@ namespace WeihanLi.Web.Authorization.Jwt; public static class DependencyInjectionExtensions { - public static IServiceCollection AddJsonWebTokenService(this IServiceCollection serviceCollection, Action optionsAction) + public static IServiceCollection AddJwtService(this IServiceCollection serviceCollection, Action optionsAction) { Guard.NotNull(serviceCollection); Guard.NotNull(optionsAction); @@ -20,7 +20,7 @@ public static IServiceCollection AddJsonWebTokenService(this IServiceCollection return serviceCollection; } - public static IServiceCollection AddJsonWebTokenServiceWithJwtBearerAuth(this IServiceCollection serviceCollection, Action optionsAction, Action jwtBearerOptionsSetup = null) + public static IServiceCollection AddJwtServiceWithJwtBearerAuth(this IServiceCollection serviceCollection, Action optionsAction, Action jwtBearerOptionsSetup = null) { Guard.NotNull(serviceCollection); Guard.NotNull(optionsAction); @@ -29,6 +29,6 @@ public static IServiceCollection AddJsonWebTokenServiceWithJwtBearerAuth(this IS serviceCollection.Configure(jwtBearerOptionsSetup); } serviceCollection.ConfigureOptions(); - return serviceCollection.AddJsonWebTokenService(optionsAction); + return serviceCollection.AddJwtService(optionsAction); } } From 8dd7d05fca98859b3082c87c3585b420e7ed90d8 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Tue, 25 Jun 2024 00:04:49 +0800 Subject: [PATCH 08/21] add auth sample for config inspector --- samples/WeihanLi.Web.Extensions.Samples/Program.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/samples/WeihanLi.Web.Extensions.Samples/Program.cs b/samples/WeihanLi.Web.Extensions.Samples/Program.cs index 7282ab3..6ffd429 100644 --- a/samples/WeihanLi.Web.Extensions.Samples/Program.cs +++ b/samples/WeihanLi.Web.Extensions.Samples/Program.cs @@ -137,10 +137,15 @@ options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); }); -app.MapConfigInspector().ShortCircuit(); - app.UseAuthentication(); app.UseAuthorization(); + +app.MapConfigInspector() + // .RequireAuthorization(x => x + // .AddAuthenticationSchemes("ApiKey") + // .RequireAuthenticatedUser() + // ) + ; app.MapControllers(); await app.RunAsync(); From 73539a56a9a5f840475051c6858e94690c3584fd Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Tue, 25 Jun 2024 09:10:50 +0800 Subject: [PATCH 09/21] feat: config inspector support configKey filter --- .../Extensions/EndpointExtensions.cs | 2 +- .../Extensions/MiddlewareExtension.cs | 2 +- .../Middleware/ConfigInspectorMiddleware.cs | 24 ++++++++++++------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs index 76ef4c9..5c15dee 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs @@ -20,7 +20,7 @@ public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteB ArgumentNullException.ThrowIfNull(endpointRouteBuilder); var app = endpointRouteBuilder.CreateApplicationBuilder(); var pipeline = app.UseConfigInspector(Configure).Build(); - return endpointRouteBuilder.MapGet(path, pipeline); + return endpointRouteBuilder.MapGet($"{path}/{{configKey?}}", pipeline); void Configure(ConfigInspectorOptions options) { diff --git a/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs b/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs index 8d17680..444bacc 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs @@ -87,7 +87,7 @@ public static IApplicationBuilder UseWhenFeatureEnabled( /// /// Use ConfigInspector to inspect config when necessary /// - public static IApplicationBuilder UseConfigInspector(this IApplicationBuilder app, + internal static IApplicationBuilder UseConfigInspector(this IApplicationBuilder app, Action optionsConfigure = null) { ArgumentNullException.ThrowIfNull(app); diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index 13bb769..38a1de6 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -27,11 +27,6 @@ internal sealed class ConfigInspectorMiddleware(RequestDelegate next) { public Task InvokeAsync(HttpContext httpContext, IOptions inspectorOptions) { - if (httpContext.Request.Path.ToString() != inspectorOptions.Value.Path) - { - return next(httpContext); - } - var configuration = httpContext.RequestServices.GetRequiredService(); if (configuration is not IConfigurationRoot configurationRoot) { @@ -39,18 +34,29 @@ public Task InvokeAsync(HttpContext httpContext, IOptions 0 } configKeyName) + { + configKey = configKeyName; + } + var inspectorOptionsValue = inspectorOptions.Value; - var configs = GetConfig(configurationRoot, inspectorOptionsValue); + var configs = GetConfig(configurationRoot, inspectorOptionsValue, configKey); if (inspectorOptionsValue.ConfigRenderer is null) return httpContext.Response.WriteAsJsonAsync(configs); return inspectorOptionsValue.ConfigRenderer.Invoke(httpContext, configs); } - private static ConfigModel[] GetConfig(IConfigurationRoot configurationRoot, ConfigInspectorOptions options) + private static ConfigModel[] GetConfig(IConfigurationRoot configurationRoot, ConfigInspectorOptions options, + string configKey) { - var allKeys = configurationRoot.AsEnumerable() - .ToDictionary(x => x.Key, _ => false); + var hasConfigKeyFilter = string.IsNullOrEmpty(configKey); + var allKeys = hasConfigKeyFilter + ? configurationRoot.AsEnumerable() + .ToDictionary(x => x.Key, _ => false) + : new() { { configKey, false } }; var providers = GetConfigProviders(configurationRoot); var config = new ConfigModel[providers.Count]; From b85d12752d0f3bf21f17e84952a5819423e98422 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sat, 29 Jun 2024 23:16:28 +0800 Subject: [PATCH 10/21] refactor: use collection expression --- .../ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs | 2 +- .../HeaderAuthentication/HeaderAuthenticationHandler.cs | 4 ++-- .../QueryAuthentication/QueryAuthenticationHandler.cs | 4 ++-- .../ParamsProtection/ParamsProtectionOptions.cs | 2 +- src/WeihanLi.Web.Extensions/Pager/PagedListModel.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs index d14244e..c2b2701 100644 --- a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs +++ b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs @@ -41,7 +41,7 @@ protected override async Task HandleAuthenticateAsync() var claims = new[] { new Claim("issuer", ClaimsIssuer), - }.Union(Options.ClaimsGenerator?.Invoke(Context, Options) ?? Array.Empty()); + }.Union(Options.ClaimsGenerator?.Invoke(Context, Options) ?? []); return AuthenticateResult.Success( new AuthenticationTicket( new ClaimsPrincipal(new[] diff --git a/src/WeihanLi.Web.Extensions/Authentication/HeaderAuthentication/HeaderAuthenticationHandler.cs b/src/WeihanLi.Web.Extensions/Authentication/HeaderAuthentication/HeaderAuthenticationHandler.cs index 62cfe96..cf81163 100644 --- a/src/WeihanLi.Web.Extensions/Authentication/HeaderAuthentication/HeaderAuthenticationHandler.cs +++ b/src/WeihanLi.Web.Extensions/Authentication/HeaderAuthentication/HeaderAuthenticationHandler.cs @@ -37,7 +37,7 @@ protected override async Task HandleAuthenticateAsync() if (Request.Headers.TryGetValue(Options.UserRolesHeaderName, out var userRolesValues)) { var userRoles = userRolesValues.ToString() - .Split(new[] { Options.Delimiter }, StringSplitOptions.RemoveEmptyEntries); + .Split([Options.Delimiter], StringSplitOptions.RemoveEmptyEntries); claims.AddRange(userRoles.Select(r => new Claim(ClaimTypes.Role, r))); } @@ -47,7 +47,7 @@ protected override async Task HandleAuthenticateAsync() { if (Request.Headers.TryGetValue(headerToClaim.Key, out var headerValues)) { - foreach (var val in headerValues.ToString().Split(new[] { Options.Delimiter }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var val in headerValues.ToString().Split([Options.Delimiter], StringSplitOptions.RemoveEmptyEntries)) { claims.Add(new Claim(headerToClaim.Value, val)); } diff --git a/src/WeihanLi.Web.Extensions/Authentication/QueryAuthentication/QueryAuthenticationHandler.cs b/src/WeihanLi.Web.Extensions/Authentication/QueryAuthentication/QueryAuthenticationHandler.cs index 67b3bbe..472fa93 100644 --- a/src/WeihanLi.Web.Extensions/Authentication/QueryAuthentication/QueryAuthenticationHandler.cs +++ b/src/WeihanLi.Web.Extensions/Authentication/QueryAuthentication/QueryAuthenticationHandler.cs @@ -38,7 +38,7 @@ protected override async Task HandleAuthenticateAsync() if (Request.Query.TryGetValue(Options.UserRolesQueryKey, out var userRolesValues)) { var userRoles = userRolesValues.ToString() - .Split(new[] { Options.Delimiter }, StringSplitOptions.RemoveEmptyEntries); + .Split([Options.Delimiter], StringSplitOptions.RemoveEmptyEntries); claims.AddRange(userRoles.Select(r => new Claim(ClaimTypes.Role, r))); } if (Options.AdditionalQueryToClaims.Count > 0) @@ -47,7 +47,7 @@ protected override async Task HandleAuthenticateAsync() { if (Request.Query.TryGetValue(queryToClaim.Key, out var queryValues)) { - foreach (var val in queryValues.ToString().Split(new[] { Options.Delimiter }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var val in queryValues.ToString().Split([Options.Delimiter], StringSplitOptions.RemoveEmptyEntries)) { claims.Add(new Claim(queryToClaim.Value, val)); } diff --git a/src/WeihanLi.Web.Extensions/DataProtection/ParamsProtection/ParamsProtectionOptions.cs b/src/WeihanLi.Web.Extensions/DataProtection/ParamsProtection/ParamsProtectionOptions.cs index 07f9446..bbdef0c 100644 --- a/src/WeihanLi.Web.Extensions/DataProtection/ParamsProtection/ParamsProtectionOptions.cs +++ b/src/WeihanLi.Web.Extensions/DataProtection/ParamsProtection/ParamsProtectionOptions.cs @@ -9,7 +9,7 @@ namespace WeihanLi.Web.DataProtection.ParamsProtection; public sealed class ParamsProtectionOptions { - private string[] _protectParams = Array.Empty(); + private string[] _protectParams = []; /// /// ProtectorPurpose diff --git a/src/WeihanLi.Web.Extensions/Pager/PagedListModel.cs b/src/WeihanLi.Web.Extensions/Pager/PagedListModel.cs index c1c89e9..e5495c5 100644 --- a/src/WeihanLi.Web.Extensions/Pager/PagedListModel.cs +++ b/src/WeihanLi.Web.Extensions/Pager/PagedListModel.cs @@ -19,7 +19,7 @@ internal sealed class PagedListModel : IPagedListModel public PagedListModel(IEnumerable data, IPagerModel pager) { - Data = data?.ToArray() ?? Array.Empty(); + Data = data?.ToArray() ?? []; Pager = pager; } From 736ca30805b3f33230d77619c2d40faa14c9ca85 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sat, 29 Jun 2024 23:20:12 +0800 Subject: [PATCH 11/21] refactor: update condition --- .../ApiKeyAuthenticationHandler.cs | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs index c2b2701..bc4447d 100644 --- a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs +++ b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs @@ -36,20 +36,19 @@ protected override async Task HandleAuthenticateAsync() return AuthenticateResult.NoResult(); var validator = Options.ApiKeyValidator ?? ((_, keyValue) => Task.FromResult(string.Equals(Options.ApiKey, keyValue))); - if (await validator.Invoke(Context, keyValues.ToString())) + if (!await validator.Invoke(Context, keyValues.ToString())) + return AuthenticateResult.Fail("Invalid ApiKey"); + + var claims = new[] { - var claims = new[] - { - new Claim("issuer", ClaimsIssuer), - }.Union(Options.ClaimsGenerator?.Invoke(Context, Options) ?? []); - return AuthenticateResult.Success( - new AuthenticationTicket( - new ClaimsPrincipal(new[] - { - new ClaimsIdentity(claims, Scheme.Name) - }), Scheme.Name) - ); - } - return AuthenticateResult.Fail("Invalid ApiKey"); + new Claim("issuer", ClaimsIssuer), + }.Union(Options.ClaimsGenerator?.Invoke(Context, Options) ?? []); + return AuthenticateResult.Success( + new AuthenticationTicket( + new ClaimsPrincipal(new[] + { + new ClaimsIdentity(claims, Scheme.Name) + }), Scheme.Name) + ); } } From 92676cdeb829cabe4622642d6aa519508c5ca529 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 29 Jun 2024 15:20:53 +0000 Subject: [PATCH 12/21] Automated dotnet-format update from commit 736ca30805b3f33230d77619c2d40faa14c9ca85 on refs/heads/dev --- .../ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs index bc4447d..fed359a 100644 --- a/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs +++ b/src/WeihanLi.Web.Extensions/Authentication/ApiKeyAuthentication/ApiKeyAuthenticationHandler.cs @@ -38,7 +38,7 @@ protected override async Task HandleAuthenticateAsync() var validator = Options.ApiKeyValidator ?? ((_, keyValue) => Task.FromResult(string.Equals(Options.ApiKey, keyValue))); if (!await validator.Invoke(Context, keyValues.ToString())) return AuthenticateResult.Fail("Invalid ApiKey"); - + var claims = new[] { new Claim("issuer", ClaimsIssuer), From 8f900e04fa1cfac8c10db863bc128682ec234e5a Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 30 Jun 2024 01:30:03 +0800 Subject: [PATCH 13/21] docs: update docfx.json --- docfx.json | 55 +++++++++++++++++++----------------------------------- 1 file changed, 19 insertions(+), 36 deletions(-) diff --git a/docfx.json b/docfx.json index 212bb9c..27f9491 100644 --- a/docfx.json +++ b/docfx.json @@ -3,60 +3,43 @@ { "src": [ { + "src": "./src", "files": [ - "src/**.csproj", - "src/WeihanLi.Web.Extensions/*.cs", - "src/**/*.cs" - ], - "exclude": [ "**/bin/**", "**/obj/**" ] + "**/*.csproj" + ] } ], - "dest": "docs/api", - "disableGitFeatures": false, - "disableDefaultFilter": false + "dest": "docs/api" } ], "build": { - "content": [ + "content": [ { "files": [ - "docs/api/**.md", - "docs/api/**.yml", - "docs/api/**/toc.yml", - "toc.yml", - "*.md" + "**/*.{md,yml}" + ], + "exclude": [ + "_site/**" ] } ], "resource": [ { "files": [ - "docs/images" - ] - } - ], - "overwrite": [ - { - "files": [ - "docs/api/**.md" - ], - "exclude": [ - "obj/**", - "_site/**" + "images/**" ] } ], - "dest": "_site", - "globalMetadataFiles": [], - "fileMetadataFiles": [], + "output": "_site", "template": [ - "default" + "default", + "modern" ], - "postProcessors": [], - "markdownEngineName": "markdig", - "noLangKeyword": false, - "keepFileLink": false, - "cleanupCacheHistory": false, - "disableGitFeatures": false + "globalMetadata": { + "_appName": "WeihanLi.Web.Extensions", + "_appTitle": "WeihanLi.Web.Extensions", + "_enableSearch": true, + "pdf": false + } } } \ No newline at end of file From 761a80ee4238e70900c6fcc70a6b16a04a07db7e Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 30 Jun 2024 10:57:12 +0800 Subject: [PATCH 14/21] refactor: simplify ConfigInspectorMiddleware --- src/Directory.Build.props | 3 ++- .../Extensions/EndpointExtensions.cs | 2 +- .../Extensions/MiddlewareExtension.cs | 4 ++-- .../Middleware/ConfigInspectorMiddleware.cs | 17 ++++++++++------- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 285474c..533b9eb 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,7 +1,8 @@ - + + enable true $(NoWarn);1591 README.md diff --git a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs index 5c15dee..4a7897a 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs @@ -15,7 +15,7 @@ public static IEndpointConventionBuilder MapRuntimeInfo(this IEndpointRouteBuild } public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteBuilder endpointRouteBuilder, string path = "/config-inspector", - Action optionsConfigure = null) + Action? optionsConfigure = null) { ArgumentNullException.ThrowIfNull(endpointRouteBuilder); var app = endpointRouteBuilder.CreateApplicationBuilder(); diff --git a/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs b/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs index 444bacc..5461a47 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/MiddlewareExtension.cs @@ -14,7 +14,7 @@ public static class MiddlewareExtension /// public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder applicationBuilder) { - applicationBuilder.UseMiddleware(); + applicationBuilder.UseMiddleware(); return applicationBuilder; } @@ -88,7 +88,7 @@ public static IApplicationBuilder UseWhenFeatureEnabled( /// Use ConfigInspector to inspect config when necessary /// internal static IApplicationBuilder UseConfigInspector(this IApplicationBuilder app, - Action optionsConfigure = null) + Action? optionsConfigure = null) { ArgumentNullException.ThrowIfNull(app); if (optionsConfigure is not null) diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index 38a1de6..0d6c750 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -7,19 +7,19 @@ public sealed class ConfigInspectorOptions { public string Path { get; set; } = "/config-inspector"; public bool IncludeEmptyProviders { get; set; } - public Func ConfigRenderer { get; set; } + public Func? ConfigRenderer { get; set; } } public sealed class ConfigModel { - public string Provider { get; set; } - public ConfigItemModel[] Items { get; set; } + public string Provider { get; set; } = default!; + public ConfigItemModel[] Items { get; set; } = []; } public sealed class ConfigItemModel { - public string Key { get; set; } - public string Value { get; set; } + public string Key { get; set; } = default!; + public string? Value { get; set; } public bool Active { get; set; } } @@ -80,27 +80,30 @@ private static ConfigModel[] GetConfig(IConfigurationRoot configurationRoot, Con private static List GetConfigProviders(IConfigurationRoot configurationRoot) { +#if NET7_0_OR_GREATER var providers = new List(); foreach (var provider in configurationRoot.Providers) { + if (provider is not ChainedConfigurationProvider chainedConfigurationProvider) { providers.Add(provider); continue; } -#if NET7_0_OR_GREATER if (chainedConfigurationProvider.Configuration is not IConfigurationRoot chainsConfigurationRoot) { continue; } providers.AddRange(GetConfigProviders(chainsConfigurationRoot)); -#endif } return providers; +#else + return configurationRoot.Providers.ToList(); +#endif } private static IEnumerable GetConfig(IConfigurationProvider provider, From 6a664f98b2b0eb33da6c665ee1a4079396fb1b4c Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 30 Jun 2024 11:09:06 +0800 Subject: [PATCH 15/21] refactor: update config key filter logics --- .../Middleware/ConfigInspectorMiddleware.cs | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index 0d6c750..00d15e0 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -52,11 +52,25 @@ public Task InvokeAsync(HttpContext httpContext, IOptions x.Key, _ => false) - : new() { { configKey, false } }; + var allKeys = configurationRoot.AsEnumerable() + .ToDictionary(x => x.Key, _ => false); + + var hasConfigKeyFilter = !string.IsNullOrEmpty(configKey); + if (hasConfigKeyFilter) + { + if (allKeys.TryGetValue(configKey, out _)) + { + allKeys = new() + { + { configKey, false } + }; + } + else + { + return []; + } + } + var providers = GetConfigProviders(configurationRoot); var config = new ConfigModel[providers.Count]; From 6fc60747ac01ab785b56e1e532cda007747d3c89 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 30 Jun 2024 11:11:43 +0800 Subject: [PATCH 16/21] refactor: remove Path from ConfigInspectorOptions --- .../Extensions/EndpointExtensions.cs | 8 +------- .../Middleware/ConfigInspectorMiddleware.cs | 1 - 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs index 4a7897a..c414c7d 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs @@ -19,13 +19,7 @@ public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteB { ArgumentNullException.ThrowIfNull(endpointRouteBuilder); var app = endpointRouteBuilder.CreateApplicationBuilder(); - var pipeline = app.UseConfigInspector(Configure).Build(); + var pipeline = app.UseConfigInspector(optionsConfigure).Build(); return endpointRouteBuilder.MapGet($"{path}/{{configKey?}}", pipeline); - - void Configure(ConfigInspectorOptions options) - { - options.Path = path; - optionsConfigure?.Invoke(options); - } } } diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index 00d15e0..a50bb84 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -5,7 +5,6 @@ namespace WeihanLi.Web.Middleware; public sealed class ConfigInspectorOptions { - public string Path { get; set; } = "/config-inspector"; public bool IncludeEmptyProviders { get; set; } public Func? ConfigRenderer { get; set; } } From afa5b1159f9501bf7b1ebe02cc12e202438df3b1 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Sun, 30 Jun 2024 14:03:01 +0800 Subject: [PATCH 17/21] update ConfigInspectorMiddleware --- .../Program.cs | 41 +++++++++++++++++++ .../Extensions/EndpointExtensions.cs | 6 ++- .../Middleware/ConfigInspectorMiddleware.cs | 3 +- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/samples/WeihanLi.Web.Extensions.Samples/Program.cs b/samples/WeihanLi.Web.Extensions.Samples/Program.cs index 6ffd429..466a199 100644 --- a/samples/WeihanLi.Web.Extensions.Samples/Program.cs +++ b/samples/WeihanLi.Web.Extensions.Samples/Program.cs @@ -4,6 +4,7 @@ using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System.Reflection; +using System.Text; using System.Text.Json.Serialization; using WeihanLi.Common.Aspect; using WeihanLi.Common.Models; @@ -140,6 +141,46 @@ app.UseAuthentication(); app.UseAuthorization(); +// app.MapConfigInspector(optionsConfigure: options => +// { +// options.ConfigRenderer = async (context, configs) => +// { +// var htmlStart = """ +// +// +// Config Inspector +// +// +// +// +// +// +// +// +// +// +// +// +// """; +// var htmlEnd = "
ProviderKeyValueActive
"; +// var tbody = new StringBuilder(); +// foreach (var config in configs) +// { +// tbody.Append($"{config.Provider}"); +// foreach (var item in config.Items) +// { +// tbody.Append( +// $$"""{{item.Key}}{{item.Value}}"""); +// } +// +// tbody.AppendLine(""); +// } +// +// var responseText = $"{htmlStart}{tbody}{htmlEnd}"; +// await context.Response.WriteAsync(responseText); +// }; +// }); + app.MapConfigInspector() // .RequireAuthorization(x => x // .AddAuthenticationSchemes("ApiKey") diff --git a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs index c414c7d..ce844a4 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs @@ -14,8 +14,10 @@ public static IEndpointConventionBuilder MapRuntimeInfo(this IEndpointRouteBuild return endpointRouteBuilder.MapGet(path, () => ApplicationHelper.RuntimeInfo); } - public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteBuilder endpointRouteBuilder, string path = "/config-inspector", - Action? optionsConfigure = null) + public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteBuilder endpointRouteBuilder, + string path = "/config-inspector", + Action? optionsConfigure = null + ) { ArgumentNullException.ThrowIfNull(endpointRouteBuilder); var app = endpointRouteBuilder.CreateApplicationBuilder(); diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index a50bb84..66c8dcf 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -33,6 +33,8 @@ public Task InvokeAsync(HttpContext httpContext, IOptions 0 } configKeyName) @@ -40,7 +42,6 @@ public Task InvokeAsync(HttpContext httpContext, IOptions Date: Sun, 30 Jun 2024 06:03:58 +0000 Subject: [PATCH 18/21] Automated dotnet-format update from commit d52647fec1f905223a2ae0d47df9300789f41c2d on refs/heads/dev --- src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs | 2 +- .../Middleware/ConfigInspectorMiddleware.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs index ce844a4..8dd869e 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/EndpointExtensions.cs @@ -14,7 +14,7 @@ public static IEndpointConventionBuilder MapRuntimeInfo(this IEndpointRouteBuild return endpointRouteBuilder.MapGet(path, () => ApplicationHelper.RuntimeInfo); } - public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteBuilder endpointRouteBuilder, + public static IEndpointConventionBuilder MapConfigInspector(this IEndpointRouteBuilder endpointRouteBuilder, string path = "/config-inspector", Action? optionsConfigure = null ) diff --git a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs index 66c8dcf..e5d02ce 100644 --- a/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs +++ b/src/WeihanLi.Web.Extensions/Middleware/ConfigInspectorMiddleware.cs @@ -54,7 +54,7 @@ private static ConfigModel[] GetConfig(IConfigurationRoot configurationRoot, Con { var allKeys = configurationRoot.AsEnumerable() .ToDictionary(x => x.Key, _ => false); - + var hasConfigKeyFilter = !string.IsNullOrEmpty(configKey); if (hasConfigKeyFilter) { @@ -70,7 +70,7 @@ private static ConfigModel[] GetConfig(IConfigurationRoot configurationRoot, Con return []; } } - + var providers = GetConfigProviders(configurationRoot); var config = new ConfigModel[providers.Count]; From 63c89adaa6cdcea668e28d93bda5a83b5ed078fe Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Fri, 6 Sep 2024 23:03:10 +0800 Subject: [PATCH 19/21] feat: upgrade jwt package --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 98ef3f9..7c02a21 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,7 +10,7 @@ - +
From c9edfa0d06c888986d4401927c8a0f3cdc691f09 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Fri, 6 Sep 2024 23:13:27 +0800 Subject: [PATCH 20/21] feat: update dependencies - remove jwt dependency, fixes #39 - upgrade dependencies --- Directory.Packages.props | 18 ++++++++---------- .../Extensions/ResultExtensions.cs | 6 ++---- .../WeihanLi.Web.Extensions.csproj | 1 - 3 files changed, 10 insertions(+), 15 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 7c02a21..c72916f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,18 +4,16 @@ true - - - + + + - - - - + + - - - + + +
diff --git a/src/WeihanLi.Web.Extensions/Extensions/ResultExtensions.cs b/src/WeihanLi.Web.Extensions/Extensions/ResultExtensions.cs index 33b170e..fd4a720 100644 --- a/src/WeihanLi.Web.Extensions/Extensions/ResultExtensions.cs +++ b/src/WeihanLi.Web.Extensions/Extensions/ResultExtensions.cs @@ -21,11 +21,10 @@ public static IActionResult GetRestResult(this T result, ResultStatus status if (result is null) return new NoContentResult(); -#pragma warning disable CS0618 // Type or member is obsolete return status switch { - ResultStatus.RequestError or ResultStatus.BadRequest => new BadRequestObjectResult(result), - ResultStatus.ResourceNotFound or ResultStatus.NotFound => new NotFoundObjectResult(result), + ResultStatus.BadRequest => new BadRequestObjectResult(result), + ResultStatus.NotFound => new NotFoundObjectResult(result), ResultStatus.MethodNotAllowed => new ObjectResult(result) { StatusCode = (int)HttpStatusCode.MethodNotAllowed @@ -34,7 +33,6 @@ public static IActionResult GetRestResult(this T result, ResultStatus status ResultStatus.NoPermission or ResultStatus.Forbidden => new ObjectResult(result) { StatusCode = (int)HttpStatusCode.Forbidden }, _ => new OkObjectResult(result) }; -#pragma warning restore CS0618 // Type or member is obsolete } public static IActionResult GetRestResult(this Result result) diff --git a/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj b/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj index 6f04eb3..b0507b1 100644 --- a/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj +++ b/src/WeihanLi.Web.Extensions/WeihanLi.Web.Extensions.csproj @@ -11,7 +11,6 @@ - From 2d8681169a2e5db654ae0e25938a2fb8259cbc46 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Fri, 6 Sep 2024 23:20:43 +0800 Subject: [PATCH 21/21] build: fix build script --- build/build.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/build/build.cs b/build/build.cs index 30541b2..12b0793 100644 --- a/build/build.cs +++ b/build/build.cs @@ -1,7 +1,7 @@ -var target = CommandLineParser.Val("target", "Default", args); -var apiKey = CommandLineParser.Val("apiKey", "", args); -var stable = CommandLineParser.Val("stable", null, args).ToBoolean(); -var noPush = CommandLineParser.Val("noPush", null, args).ToBoolean(); +var target = CommandLineParser.Val("target", args, "Default"); +var apiKey = CommandLineParser.Val("apiKey", args); +var stable = CommandLineParser.BooleanVal("stable", args); +var noPush = CommandLineParser.BooleanVal("noPush", args); var branchName = EnvHelper.Val("BUILD_SOURCEBRANCHNAME", "local"); var solutionPath = "./WeihanLi.Web.Extensions.sln"; @@ -114,4 +114,4 @@ async Task ExecuteCommandAsync(string commandText, KeyValuePair[ var result = await CommandExecutor.ExecuteCommandAndOutputAsync(commandText); result.EnsureSuccessExitCode(); Console.WriteLine(); -} \ No newline at end of file +}