From 8035e553e2e303da9d9d345d88211b6803305bab Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 01:36:46 +0100 Subject: [PATCH 1/2] Refactor DI --- ReadMe.md | 18 ++ .../FeatureRegistrationExtensions.cs | 128 +++++++++++ .../RefreshTokenBuilderExtensions.cs | 30 ++- .../RuntimeAppsAuthenticationBuilder.cs | 204 ++++-------------- .../Models/RefreshTokenOptions.cs | 1 + ...erificationDependenciesStartupValidator.cs | 26 +++ .../Program.cs | 21 +- .../appsettings.json | 14 ++ .../authentication.db | Bin 0 -> 4096 bytes .../authentication.db-shm | Bin 0 -> 32768 bytes .../authentication.db-wal | Bin 0 -> 119512 bytes .../RegistrationOptionsTest.cs | 44 ++++ 12 files changed, 308 insertions(+), 178 deletions(-) create mode 100644 RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs create mode 100644 RuntimeApps.Authentication/Features/Verification/Services/VerificationDependenciesStartupValidator.cs create mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db create mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db-shm create mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db-wal create mode 100644 Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs diff --git a/ReadMe.md b/ReadMe.md index 9ac5ec7..320f6e3 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -99,6 +99,24 @@ You can add more services and customize services. Also, there are some [samples] ## External Social Logins +### Explicit feature registration and configuration + +`AddRuntimeAppsAuthentication()` registers core Identity managers, the account service, and default user mappers only. Stores and optional features are registered explicitly. The existing `UseJwt`, `AddVerificationServices`, `AddForgotPassword`, `AddRefreshToken`, and provider methods remain available as fluent APIs. + +Option sections are `Authentication:Jwt` (the existing `JwtBearerOptions` type), `Authentication:Verification`, `Authentication:ForgotPassword`, `Authentication:RefreshTokens`, and `Authentication:ExternalLogin:Google|Facebook|Microsoft`. Each feature supports configuration binding followed by an action callback. The callback runs after binding, so explicitly assigned values win while untouched values remain from configuration: + +```cs +.AddVerificationServices(builder.Configuration) +.AddVerificationServices(options => options.CodeLength = 8) +.AddForgotPassword(builder.Configuration) +.AddRefreshToken(builder.Configuration, options => options.TokenLifetime = TimeSpan.FromDays(14)) +.UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, options => options.RequireHttpsMetadata = true) +``` + +Actions alone remain supported. Defaults are supplied by each options type; configuration binding runs before callbacks; standard Options post-configuration runs afterward; feature validation runs on application startup. External provider options bind JSON values while callbacks can set non-bindable mapper delegates. Keep credentials in user secrets, environment variables, or a secret manager. + +Registrations use `TryAdd` to preserve application-provided services. Store interfaces for a single store implementation resolve the same scoped store instance. Use `AddUserMapper` to replace the selected mapper; register custom store interfaces before `AddStores` to retain your implementations. Repeating feature registration appends options configuration in call order and does not duplicate default provider/service registrations. + In many cases you want to add social login to your project, so users can quickly log in and use the application. External login needs to redirect the user to the social login pages which are not useful for API services. This repository provides an easy way to handle external login in ASP.Net core web API. You only should do: In the frontend part, you could use various libraries based on what framework you are using. For example, you could use [Angular Social Login](https://www.npmjs.com/package/@abacritt/angularx-social-login) in angular and [react-social-login diff --git a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs new file mode 100644 index 0000000..3be5dd9 --- /dev/null +++ b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs @@ -0,0 +1,128 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using RuntimeApps.Authentication.Features.Account.Services; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.ExternalLogin.Providers; +using RuntimeApps.Authentication.Features.ExternalLogin.Services; +using RuntimeApps.Authentication.Features.PasswordRecovery.Contracts; +using RuntimeApps.Authentication.Features.PasswordRecovery.Models; +using RuntimeApps.Authentication.Features.PasswordRecovery.Services; +using RuntimeApps.Authentication.Features.Registration.Contracts; +using RuntimeApps.Authentication.Features.Registration.Services; +using RuntimeApps.Authentication.Features.Verification.Contracts; +using RuntimeApps.Authentication.Features.Verification.Models; +using RuntimeApps.Authentication.Features.Verification.Services; +using RuntimeApps.Authentication.Identity.Contracts; + +namespace RuntimeApps.Authentication.DependencyInjection { + /// Opt-in feature registrations. Each method only adds the named feature's services. + public static class FeatureRegistrationExtensions { + /// Registers Identity's standard validators if the application has not supplied validators. + public static RuntimeAppsAuthenticationBuilder AddValidators(this RuntimeAppsAuthenticationBuilder builder, Action configure = null) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + builder.Services.TryAddTransient, PasswordValidator>(); + builder.Services.TryAddTransient, UserValidator>(); + builder.Services.TryAddTransient, RoleValidator>(); + if (configure != null) builder.Services.Configure(configure); + return builder; + } + public static RuntimeAppsAuthenticationBuilder AddVerificationServices(this RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => + AddVerificationServices(builder, configuration, null); + + public static RuntimeAppsAuthenticationBuilder AddVerificationServices(this RuntimeAppsAuthenticationBuilder builder, Action configureOptions = null) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => + AddVerificationServices(builder, null, configureOptions); + + private static RuntimeAppsAuthenticationBuilder AddVerificationServices(RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration, Action configure) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + var options = builder.Services.AddOptions(); + if (configuration != null) options.Bind(configuration.GetSection(VerificationOptions.SectionName)); + if (configure != null) options.Configure(configure); + options.Validate(o => { try { o.Validate(); return true; } catch (InvalidOperationException) { return false; } }, "Verification options are invalid. Check code length, lifetime, attempt count, cooldown, and send limit.").ValidateOnStart(); + builder.Services.AddDataProtection(); + builder.Services.Configure(o => o.SignIn.RequireConfirmedEmail = true); + builder.Services.TryAddSingleton(TimeProvider.System); + builder.Services.TryAddScoped, RandomVerificationCodeGenerator>(); + builder.Services.TryAddScoped, DataProtectionVerificationCodeVerifier>(); + builder.Services.TryAddScoped, VerificationWorkflowService>(); + builder.Services.TryAddScoped, VerificationWorkflowService>(); + builder.Services.TryAddScoped, RegistrationService>(); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton>()); + return builder; + } + + public static RuntimeAppsAuthenticationBuilder AddForgotPassword(this RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddForgotPasswordCore(builder, configuration, null); + public static RuntimeAppsAuthenticationBuilder AddForgotPassword(this RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration, Action configureOptions) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddForgotPasswordCore(builder, configuration, configureOptions); + public static RuntimeAppsAuthenticationBuilder AddForgotPassword(this RuntimeAppsAuthenticationBuilder builder, Action configureOptions = null) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddForgotPasswordCore(builder, null, configureOptions); + private static RuntimeAppsAuthenticationBuilder AddForgotPasswordCore(RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration, Action configure) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + var options = builder.Services.AddOptions(); + if (configuration != null) options.Bind(configuration.GetSection(ForgotPasswordOptions.SectionName)); + if (configure != null) options.Configure(configure); + options.Validate(o => { try { o.Validate(); return true; } catch (InvalidOperationException) { return false; } }, "Forgot-password options are invalid. Link mode requires an absolute HTTPS FrontendResetUrl.").ValidateOnStart(); + builder.Services.TryAddTransient>(); + builder.Services.Configure(o => o.Tokens.ProviderMap.TryAdd(TokenOptions.DefaultProvider, new TokenProviderDescriptor(typeof(DataProtectorTokenProvider)))); + builder.Services.TryAddScoped, ForgotPasswordService>(); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton>()); + return builder; + } + + public static RuntimeAppsAuthenticationBuilder UseJwt(this RuntimeAppsAuthenticationBuilder builder, string scheme, Action configure) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configure); + builder.Services.TryAddScoped, JwtProvider>(); + builder.Services.Configure(configure); + builder.Services.AddOptions(scheme).ValidateOnStart(); + builder.Authentication.AddJwtBearer(scheme, configure); + return builder; + } + + public static RuntimeAppsAuthenticationBuilder UseJwt(this RuntimeAppsAuthenticationBuilder builder, string scheme, IConfiguration configuration, Action configure = null) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configuration); + const string section = "Authentication:Jwt"; + builder.Services.TryAddScoped, JwtProvider>(); + builder.Authentication.AddJwtBearer(scheme); + var schemeOptions = builder.Services.AddOptions(scheme).Bind(configuration.GetSection(section)); + builder.Services.Configure(configuration.GetSection(section)); + if (configure != null) { + builder.Services.Configure(configure); + builder.Services.Configure(scheme, configure); + } + schemeOptions.ValidateOnStart(); + return builder; + } + + private static RuntimeAppsAuthenticationBuilder AddProvider(RuntimeAppsAuthenticationBuilder b, IConfiguration c, Action configure) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable + where TOption : BaseExternalLoginOption, new() where TProvider : class, IExternalLoginProvider { + ArgumentNullException.ThrowIfNull(b); + var o = b.Services.AddOptions(); + if (c != null) o.Bind(c.GetSection(TOptionSection.Name)); + if (configure != null) o.Configure(configure); + o.Validate(x => !string.IsNullOrWhiteSpace(x.ClientId) && !string.IsNullOrWhiteSpace(x.ClientSecret), "External login requires ClientId and ClientSecret.").ValidateOnStart(); + b.Services.TryAddTransient, TProvider>(); + b.Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); + return b; + } + private static class TOptionSection { public static string Name => typeof(T).Name.StartsWith("Google", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Google" : typeof(T).Name.StartsWith("Facebook", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Facebook" : "Authentication:ExternalLogin:Microsoft"; } + public static RuntimeAppsAuthenticationBuilder AddGoogleExternalLogin(this RuntimeAppsAuthenticationBuilder b, Action> configure) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, GoogleExternalLoginProvider>(b, null, configure); + public static RuntimeAppsAuthenticationBuilder AddGoogleExternalLogin(this RuntimeAppsAuthenticationBuilder b, IConfiguration c, Action> configure = null) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, GoogleExternalLoginProvider>(b, c, configure); + public static RuntimeAppsAuthenticationBuilder AddFacebookExternalLogin(this RuntimeAppsAuthenticationBuilder b, Action> configure) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, FacebookExternalLoginProvider>(b, null, configure); + public static RuntimeAppsAuthenticationBuilder AddFacebookExternalLogin(this RuntimeAppsAuthenticationBuilder b, IConfiguration c, Action> configure = null) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, FacebookExternalLoginProvider>(b, c, configure); + public static RuntimeAppsAuthenticationBuilder AddMicrosoftExternalLogin(this RuntimeAppsAuthenticationBuilder b, Action> configure) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, MicrosoftExternalLoginProvider>(b, null, configure); + public static RuntimeAppsAuthenticationBuilder AddMicrosoftExternalLogin(this RuntimeAppsAuthenticationBuilder b, IConfiguration c, Action> configure = null) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => AddProvider, MicrosoftExternalLoginProvider>(b, c, configure); + } +} diff --git a/RuntimeApps.Authentication/DependencyInjection/RefreshTokenBuilderExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/RefreshTokenBuilderExtensions.cs index 7d97244..2162f66 100644 --- a/RuntimeApps.Authentication/DependencyInjection/RefreshTokenBuilderExtensions.cs +++ b/RuntimeApps.Authentication/DependencyInjection/RefreshTokenBuilderExtensions.cs @@ -1,11 +1,27 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; using RuntimeApps.Authentication.Features.RefreshTokens.Models; using RuntimeApps.Authentication.Features.RefreshTokens.Services; namespace RuntimeApps.Authentication.DependencyInjection { public static class RefreshTokenBuilderExtensions { + public static RuntimeAppsAuthenticationBuilder AddRefreshToken( + this RuntimeAppsAuthenticationBuilder builder, IConfiguration configuration, + Action configure = null) + where TUser : Microsoft.AspNetCore.Identity.IdentityUser, new() + where TRole : Microsoft.AspNetCore.Identity.IdentityRole + where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configuration); + var configuredOptions = builder.Services.AddOptions() + .Bind(configuration.GetSection(RefreshTokenOptions.SectionName)); + if (configure != null) configuredOptions.Configure(configure); + AddServices(builder, configuredOptions); + return builder; + } /// /// Enables refresh-token management. A store must also be registered, either by the EF /// integration package or by the application. Without this call, refresh-token services @@ -19,8 +35,17 @@ public static RuntimeAppsAuthenticationBuilder AddRefreshTok where TKey : IEquatable { ArgumentNullException.ThrowIfNull(builder); - builder.Services.AddOptions() - .Configure(configure ?? (_ => { })) + var configuredOptions = builder.Services.AddOptions(); + configuredOptions.Configure(configure ?? (_ => { })); + AddServices(builder, configuredOptions); + return builder; + } + + private static void AddServices(RuntimeAppsAuthenticationBuilder builder, OptionsBuilder configuredOptions) + where TUser : Microsoft.AspNetCore.Identity.IdentityUser, new() + where TRole : Microsoft.AspNetCore.Identity.IdentityRole + where TKey : IEquatable { + configuredOptions .Validate(options => options.TokenLifetime > TimeSpan.Zero, "Refresh-token lifetime must be greater than zero.") .Validate(options => options.RefreshRequestsPerMinute > 0, @@ -47,7 +72,6 @@ public static RuntimeAppsAuthenticationBuilder AddRefreshTok builder.Services.TryAddSingleton(); builder.Services.TryAddEnumerable( ServiceDescriptor.Singleton>()); - return builder; } } } diff --git a/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs index 885cdb3..aece04c 100644 --- a/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs @@ -1,53 +1,36 @@ using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using RuntimeApps.Authentication.Features.Account.Contracts; -using RuntimeApps.Authentication.Features.Account.Services; -using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; -using RuntimeApps.Authentication.Features.ExternalLogin.Models; -using RuntimeApps.Authentication.Features.ExternalLogin.Providers; -using RuntimeApps.Authentication.Features.ExternalLogin.Services; -using RuntimeApps.Authentication.Features.PasswordRecovery.Contracts; -using RuntimeApps.Authentication.Features.PasswordRecovery.Models; -using RuntimeApps.Authentication.Features.PasswordRecovery.Services; -using RuntimeApps.Authentication.Features.Registration.Contracts; -using RuntimeApps.Authentication.Features.Registration.Services; -using RuntimeApps.Authentication.Features.Verification.Contracts; -using RuntimeApps.Authentication.Features.Verification.Models; -using RuntimeApps.Authentication.Features.Verification.Services; using RuntimeApps.Authentication.Identity; using RuntimeApps.Authentication.Identity.Contracts; using RuntimeApps.Authentication.Identity.Models; namespace RuntimeApps.Authentication.DependencyInjection { + /// Builder for RuntimeApps core Identity integration and user mapping. public class RuntimeAppsAuthenticationBuilder where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { - public RuntimeAppsAuthenticationBuilder(AuthenticationBuilder authenticationBuilder) { - Authentication = authenticationBuilder ?? throw new NullReferenceException(nameof(authenticationBuilder)); + ArgumentNullException.ThrowIfNull(authenticationBuilder); + Authentication = authenticationBuilder; Services = authenticationBuilder.Services; } - public AuthenticationBuilder Authentication { get; set; } - public IServiceCollection Services { get; set; } + public AuthenticationBuilder Authentication { get; } + public IServiceCollection Services { get; } + /// Registers the Identity managers and RuntimeApps account service. Optional workflows are opt-in. public RuntimeAppsAuthenticationBuilder AddAuthenticationServices() { - Services.TryAddScoped, UserAccountService>(); - Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); - + Services.TryAddScoped, Features.Account.Services.UserAccountService>(); Services.AddHttpContextAccessor(); Services.AddHttpClient(); - // Identity services Services.TryAddScoped, UserValidator>(); Services.TryAddScoped, PasswordValidator>(); Services.TryAddScoped, PasswordHasher>(); Services.TryAddScoped(); Services.TryAddScoped, RoleValidator>(); - // No interface for the error describer so we can add errors without rev'ing the interface Services.TryAddScoped(); Services.TryAddScoped>(); Services.TryAddScoped>(); @@ -59,162 +42,63 @@ public RuntimeAppsAuthenticationBuilder AddAuthenticationSer Services.TryAddScoped, RuntimeAppsSignInManager>(); Services.TryAddScoped>(); Services.TryAddScoped, RuntimeAppsRoleManager>(); - AddBuiltInUserMappers(); return this; } - /// - /// Registers the default verification workflow, secure code generation, and protected verifier. - /// The application must also register a persistent IVerificationRequestStore and a delivery sender. - /// - public RuntimeAppsAuthenticationBuilder AddVerificationServices( - Action configureOptions = null) { - Services.AddDataProtection(); - Services.AddOptions(); - Services.AddOptions() - .Configure(options => configureOptions?.Invoke(options)) - .Validate(options => options.CodeLength is >= 4 and <= 12 && - options.CodeLifetime > TimeSpan.Zero && - options.MaximumFailedAttempts > 0 && - options.ResendCooldown >= TimeSpan.Zero && - options.MaximumSendsPerHour > 0, - "Verification options contain invalid values.") - .ValidateOnStart(); - - Services.Configure(options => options.SignIn.RequireConfirmedEmail = true); - Services.TryAddSingleton(TimeProvider.System); - Services.TryAddScoped, RandomVerificationCodeGenerator>(); - Services.TryAddScoped, DataProtectionVerificationCodeVerifier>(); - Services.TryAddScoped, VerificationWorkflowService>(); - Services.TryAddScoped, VerificationWorkflowService>(); - Services.TryAddScoped, RegistrationService>(); - return this; - } - - - /// - /// Registers the optional forgot-password workflow. Map its endpoints separately with - /// MapForgotPasswordApi; they are never added implicitly by other endpoint mappings. - /// - public RuntimeAppsAuthenticationBuilder AddForgotPassword( - Action configureOptions = null) { - Services.AddOptions() - .Configure(options => configureOptions?.Invoke(options)) - .Validate(options => { - try { options.Validate(); return true; } catch(InvalidOperationException) { return false; } - }, "Forgot-password options are invalid.") - .ValidateOnStart(); - // Password-reset operations use ASP.NET Core Identity's token provider. Register - // the standard Data Protection provider when the application has not supplied one. - Services.TryAddTransient>(); - Services.Configure(options => { - options.Tokens.ProviderMap.TryAdd( - TokenOptions.DefaultProvider, - new TokenProviderDescriptor(typeof(DataProtectorTokenProvider))); - }); - Services.TryAddScoped, ForgotPasswordService>(); - return this; - } - - public RuntimeAppsAuthenticationBuilder UseJwt(string authenticationScheme, Action configureOptions) { - Services.TryAddScoped, JwtProvider>(); - Services.Configure(configureOptions); - Authentication.AddJwtBearer(authenticationScheme, configureOptions); - return this; - } - - /// - /// Registers the mapper used by the API endpoints to convert between and . - /// Replaces any mapper already registered for the same DTO (including the built-in one), so the last call wins. - /// public RuntimeAppsAuthenticationBuilder AddUserMapper(ServiceLifetime lifetime = ServiceLifetime.Scoped) - where TUserDto : class - where TMapper : class, IUserMapper { + where TUserDto : class where TMapper : class, IUserMapper { Services.Replace(ServiceDescriptor.Describe(typeof(IUserMapper), typeof(TMapper), lifetime)); return this; } - - /// - /// Registers a mapper built from two delegates. Use it for quick inline mapping or to wrap any mapper library. - /// - public RuntimeAppsAuthenticationBuilder AddUserMapper(Func toDto, Func toUser) - where TUserDto : class { + public RuntimeAppsAuthenticationBuilder AddUserMapper(Func toDto, Func toUser) where TUserDto : class { + ArgumentNullException.ThrowIfNull(toDto); ArgumentNullException.ThrowIfNull(toUser); Services.Replace(ServiceDescriptor.Singleton>(new DelegateUserMapper(toDto, toUser))); return this; } - - /// - /// Registers for a DTO derived from . - /// (and for string keys) are already covered without calling this. - /// - public RuntimeAppsAuthenticationBuilder AddDefaultUserMapper() - where TUserDto : IdentityUserDto, new() { - return AddUserMapper>(); - } - - public RuntimeAppsAuthenticationBuilder AddGoogleExternalLogin(Action> option) { - Services.TryAddTransient, GoogleExternalLoginProvider>(); - Services.Configure(option); - return this; - } - - public RuntimeAppsAuthenticationBuilder AddFacebookExternalLogin(Action> option) { - Services.AddTransient, FacebookExternalLoginProvider>(); - Services.Configure(option); - return this; - } - - public RuntimeAppsAuthenticationBuilder AddMicrosoftExternalLogin(Action> option) { - Services.AddTransient, MicrosoftExternalLoginProvider>(); - Services.Configure(option); - return this; - } - - public RuntimeAppsAuthenticationBuilder AddValidators(Action identityOption = null) { - Services.TryAddTransient, PasswordValidator>(); - Services.TryAddTransient, UserValidator>(); - Services.TryAddTransient, RoleValidator>(); - if(identityOption != null) - Services.Configure(identityOption); - return this; - } + public RuntimeAppsAuthenticationBuilder AddDefaultUserMapper() where TUserDto : IdentityUserDto, new() => AddUserMapper>(); + + // Compatibility wrappers keep the original public builder surface while implementation lives in focused extensions. + public RuntimeAppsAuthenticationBuilder AddVerificationServices(Action configureOptions = null) => + FeatureRegistrationExtensions.AddVerificationServices(this, configureOptions); + public RuntimeAppsAuthenticationBuilder AddForgotPassword(Action configureOptions = null) => + FeatureRegistrationExtensions.AddForgotPassword(this, configureOptions); + public RuntimeAppsAuthenticationBuilder UseJwt(string scheme, Action configure) => + FeatureRegistrationExtensions.UseJwt(this, scheme, configure); + public RuntimeAppsAuthenticationBuilder AddValidators(Action configure = null) => + FeatureRegistrationExtensions.AddValidators(this, configure); + public RuntimeAppsAuthenticationBuilder AddGoogleExternalLogin(Action> configure) => + FeatureRegistrationExtensions.AddGoogleExternalLogin(this, configure); + public RuntimeAppsAuthenticationBuilder AddFacebookExternalLogin(Action> configure) => + FeatureRegistrationExtensions.AddFacebookExternalLogin(this, configure); + public RuntimeAppsAuthenticationBuilder AddMicrosoftExternalLogin(Action> configure) => + FeatureRegistrationExtensions.AddMicrosoftExternalLogin(this, configure); public RuntimeAppsAuthenticationBuilder AddStores() where TUserStoreImpl : UserStoreBase, IdentityUserRole, IdentityUserLogin, IdentityUserToken, IdentityRoleClaim>, IProtectedUserStore where TRoleStoreImpl : class, IRoleClaimStore { - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - Services.TryAddScoped, TUserStoreImpl>(); - - Services.TryAddScoped, TRoleStoreImpl>(); - Services.TryAddScoped, TRoleStoreImpl>(); + Services.TryAddScoped(); + Services.TryAddScoped(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); AddUserStore, TUserStoreImpl>(); + AddUserStore, TUserStoreImpl>(); + Services.TryAddScoped>(sp => sp.GetRequiredService()); + Services.TryAddScoped>(sp => sp.GetRequiredService()); return this; } - // Out-of-the-box mappers, so the endpoints work without any mapper setup. - // They are TryAdd, so AddUserMapper / AddDefaultUserMapper always override them. + private void AddUserStore() where TImplementation : class, TStore where TStore : class => + Services.TryAddScoped(sp => sp.GetRequiredService()); + private void AddBuiltInUserMappers() { Services.TryAddScoped>, DefaultIdentityUserMapper, TKey>>(); - - // IdentityUserDto (non-generic) only exists for string keys - if(typeof(TKey) == typeof(string)) { - Services.TryAdd(ServiceDescriptor.Scoped( - typeof(IUserMapper), - typeof(DefaultIdentityUserMapper<,,>).MakeGenericType(typeof(TUser), typeof(IdentityUserDto), typeof(TKey)))); - } + if (typeof(TKey) == typeof(string)) + Services.TryAdd(ServiceDescriptor.Scoped(typeof(IUserMapper), typeof(DefaultIdentityUserMapper<,,>).MakeGenericType(typeof(TUser), typeof(IdentityUserDto), typeof(TKey)))); } } } diff --git a/RuntimeApps.Authentication/Features/RefreshTokens/Models/RefreshTokenOptions.cs b/RuntimeApps.Authentication/Features/RefreshTokens/Models/RefreshTokenOptions.cs index 02dd002..f4f70d7 100644 --- a/RuntimeApps.Authentication/Features/RefreshTokens/Models/RefreshTokenOptions.cs +++ b/RuntimeApps.Authentication/Features/RefreshTokens/Models/RefreshTokenOptions.cs @@ -2,6 +2,7 @@ namespace RuntimeApps.Authentication.Features.RefreshTokens.Models { public sealed class RefreshTokenOptions { + public const string SectionName = "Authentication:RefreshTokens"; /// Maximum lifetime of a refresh token. Defaults to 30 days. public TimeSpan TokenLifetime { get; set; } = TimeSpan.FromDays(30); diff --git a/RuntimeApps.Authentication/Features/Verification/Services/VerificationDependenciesStartupValidator.cs b/RuntimeApps.Authentication/Features/Verification/Services/VerificationDependenciesStartupValidator.cs new file mode 100644 index 0000000..b52ab9c --- /dev/null +++ b/RuntimeApps.Authentication/Features/Verification/Services/VerificationDependenciesStartupValidator.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using RuntimeApps.Authentication.Features.PasswordRecovery.Contracts; +using RuntimeApps.Authentication.Features.Verification.Contracts; +using RuntimeApps.Authentication.Identity.Contracts; + +namespace RuntimeApps.Authentication.Features.Verification.Services; + +internal sealed class VerificationDependenciesStartupValidator(IServiceScopeFactory scopeFactory) : IHostedService + where TUser : class where TKey : IEquatable { + public Task StartAsync(CancellationToken cancellationToken) { + using var scope = scopeFactory.CreateScope(); + var services = scope.ServiceProvider; + Require>(services, "Register a persistent verification request store (for example, AddVerificationRequestStore)."); + Require>(services, "Register an IVerificationSender delivery service."); + Require>(services, "Register the verification feature with AddVerificationServices."); + return Task.CompletedTask; + } + private static void Require(IServiceProvider services, string guidance) where TService : notnull { + try { _ = services.GetRequiredService(); } + catch (InvalidOperationException exception) { + throw new InvalidOperationException($"The verification feature is enabled but required service '{typeof(TService).Name}' is missing. {guidance}", exception); + } + } + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index e3bba67..c64186a 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -40,15 +40,12 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //Add default services of RuntimeApps application .AddRuntimeAppsAuthentication, IdentityRole, int>() + .AddVerificationServices(builder.Configuration) .AddVerificationServices(options => { + // This code override takes precedence over Authentication:Verification:CodeLength. options.CodeLength = 6; - options.CodeLifetime = TimeSpan.FromMinutes(10); - options.MaximumFailedAttempts = 5; - options.ResendCooldown = TimeSpan.FromSeconds(60); - options.MaximumSendsPerHour = 5; - options.RequireEmailVerificationForExternalLogins = false; }) - .AddForgotPassword(options => { + .AddForgotPassword(builder.Configuration, options => { // Choose Link and configure FrontendResetUrl to enable frontend-hosted reset links. options.Method = ForgotPasswordMethod.VerificationCode; }) @@ -78,23 +75,17 @@ //Add basic validations which is implemeted by ASP.Net core identity .AddValidators() //Add validator services of google authentication - .AddGoogleExternalLogin(option => { - option.ClientId = builder.Configuration["Authentication:Google:ClientId"]; - option.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; + .AddGoogleExternalLogin(builder.Configuration, option => { // Mapper of google model to user model option.Mapper = (data) => GoogleExternalLoginOption>.UserIdentityMapper, int>(data); }) //Add validator services of facebook authentication - .AddFacebookExternalLogin(option => { - option.ClientId = builder.Configuration["Authentication:Facebook:AppId"]; - option.ClientSecret = builder.Configuration["Authentication:Facebook:AppSecret"]; + .AddFacebookExternalLogin(builder.Configuration, option => { // Mapper of facebook model to user model option.Mapper = (data) => FacebookExternalLoginOption>.UserIdentityMapper, int>(data); }) //Add validator services of microsoft authentication - .AddMicrosoftExternalLogin(option => { - option.ClientId = builder.Configuration["Authentication:Microsoft:ClientId"]; - option.ClientSecret = builder.Configuration["Authentication:Microsoft:ClientSecret"]; + .AddMicrosoftExternalLogin(builder.Configuration, option => { // Mapper of microsot model to user model option.Mapper = (data) => MicrosoftExternalLoginOption>.UserIdentityMapper, int>(data); }); diff --git a/Samples/RuntimeApps.Authentication.Sample/appsettings.json b/Samples/RuntimeApps.Authentication.Sample/appsettings.json index 970a9a9..772cd22 100644 --- a/Samples/RuntimeApps.Authentication.Sample/appsettings.json +++ b/Samples/RuntimeApps.Authentication.Sample/appsettings.json @@ -17,6 +17,12 @@ }, "Authentication": { "Verification": { + "CodeLength": 7, + "CodeLifetime": "00:10:00", + "MaximumFailedAttempts": 5, + "ResendCooldown": "00:01:00", + "MaximumSendsPerHour": 5, + "RequireEmailVerificationForExternalLogins": false, "Smtp": { "Host": "localhost", "Port": 1025, @@ -24,6 +30,14 @@ "FromAddress": "noreply@example.com", "FromName": "RuntimeApps Authentication Sample" } + }, + "ForgotPassword": { + "Method": "VerificationCode" + }, + "RefreshTokens": { + "TokenLifetime": "30.00:00:00", + "RevokeFamilyOnReuse": true, + "RefreshRequestsPerMinute": 30 } } } diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db b/Samples/RuntimeApps.Authentication.Sample/authentication.db new file mode 100644 index 0000000000000000000000000000000000000000..cc04c103cdf5416b37dcbcd114b399f735eadcdf GIT binary patch literal 4096 zcmWFz^vNtqRY=P(%1ta$FlG>7U}9o$P*7lCU|@t|AVoG{WYC*>h8Lt=fNV2HHI9bB nXb6mkz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeDP#6LLQSS$G literal 0 HcmV?d00001 diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db-shm b/Samples/RuntimeApps.Authentication.Sample/authentication.db-shm new file mode 100644 index 0000000000000000000000000000000000000000..a26145014016ef99f886b7075070f14f2a1e545e GIT binary patch literal 32768 zcmeI*y-k~86b0Zf0m5$*2XJEkMo7mH=~#n;DiswYAR!ty@B&CkkupLG#0Km@ZSE;7 zQNAf?zV|uOk!;Jdt;hYjv*(|~G9QLva#Byyi|gBmr@!;d`Q!P`%b%<1@B6dG>92ox zv;Tbm^0V`qi#K`udLGwz44P%ZdJFdJJrwCFV(NrN%dQGx4Ku| zuTHDqt3Rr<>Ou9edQ?5G=JyBz0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK;XRuvU?yc0$H7qaS3Gc zLs|r~w<6;b$kvUt2xMtU#wC!ICutGL#+HmrAp2(0B9L`C8J9qo{iH=8yNWU{foxhz zi$E4dWn2Q*TwDLoZ0QPtJ_WKOEd=@$$bPyI=u;q<1B5`I0=bzX1o{-nwHP7Lr$Fu` z34uNZav@9z^eK?rctW60fn0?Y0(}bP9;y)NQy`asg+QMIxq&SN`V`3ZcWDuL1%a0? AZvX%Q literal 0 HcmV?d00001 diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db-wal b/Samples/RuntimeApps.Authentication.Sample/authentication.db-wal new file mode 100644 index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>&$$|pHY>LDXctGd9MYvg6GtHk$;t<%r_GCa_K(X-auwZR)o!B!^QS}Ua%{dD&7Iw}qqM0X(X=XMh@2MMU?}^+Hk3_P zYELA#R(6xA>`WpyJ;RfmE^S!b*;_k0*VPT5NUSH`y>r^T)Q-m15hdH%&Z@JUCqc8- z^Ny{7Y`hxlw<$$Cpc*zEqIWIKbF}0uJMc=sR!??@OE(9Cw-0+4hjj;H=MiJ{hLv^W zNewo1fSS^#xHX3>LzY~uY$*KDxU&Yc;0~?A%@TM%JSDra&+<>Rr68zJK#N3#AduTLKu# zH#d=>rlL~>BhxlDh8MkSTxBpXb2w!%lGinnp{Al!1|!ohLt)5pty^>q6carlXtT9W zZmrp2?c7pR+TK-_w&hy-u|uNqU_*^*1ygYPl~K2nZ*tMtDp9>Lr!P^uFIkyXW250v z_}VWh-qvs2fT`F{e^NskR~jvcF`fra(d(`#8rej&72Z+Q9f;k_Vy9*uR~+o8I~`do zxK31aQH+UaKXPhc)@#Kf6P96O^F+DpEhVE_+i1Tbcg1%1`GePT(-3!1MYTGjYHxtD zan#@jD9xhh_5Yjipzc|{vir&ATyDFBYNU|=+VtLcU2dWNpI#na+`Tyv%uae2AFQst z&F_e1jmsM#Dzk_p*!~d6&P5zR$C`z+=&8ejB)T`x%@U=)@=obOHeo009sH0T2KI z5C8!X009sHfjRe72?Rg@1V8`;KmY_l00ck) z1V8`;>IiJ4DJ(9qNp_*1V8`;KmY_l00ck)1V8`;KmY_fk-#lfDHa#FxbeYPo}YN>JmLbKXlm#L z0w4eaAOHd&00JNY0w4eaAOHe&1a74%EH3cG^!k@}UD literal 0 HcmV?d00001 diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs new file mode 100644 index 0000000..7ce9c14 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs @@ -0,0 +1,44 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Features.Verification.Models; + +namespace RuntimeApps.Authentication.Test; + +public class RegistrationOptionsTest { + [Fact] + public void VerificationConfiguration_CombinesBindingThenCodeOverrides() { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + [$"{VerificationOptions.SectionName}:CodeLength"] = "8", + [$"{VerificationOptions.SectionName}:MaximumFailedAttempts"] = "9" + }).Build(); + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .AddVerificationServices(configuration) + .AddVerificationServices(o => o.CodeLength = 10); + + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + Assert.Equal(10, options.CodeLength); + Assert.Equal(9, options.MaximumFailedAttempts); + } + + [Fact] + public void CoreRegistration_DoesNotRegisterOptionalVerificationServices() { + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication(); + using var provider = services.BuildServiceProvider(); + Assert.False(provider.GetRequiredService().IsService(typeof(Features.Verification.Contracts.IVerificationWorkflowService))); + } + + [Fact] + public void InvalidVerificationOptions_FailOptionsValidation() { + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .AddVerificationServices(options => options.CodeLength = 3); + using var provider = services.BuildServiceProvider(); + Assert.Throws(() => provider.GetRequiredService>().Value); + } +} From b1744888cd3a7c89b7a09dbc72551594d76361dc Mon Sep 17 00:00:00 2001 From: Amin Date: Sat, 21 Nov 2026 01:49:49 +0100 Subject: [PATCH 2/2] Apply fix comments --- .gitignore | 5 +- ReadMe.md | 24 ++-- .../FeatureRegistrationExtensions.cs | 19 +-- .../Features/Account/Services/JwtProvider.cs | 4 + .../Program.cs | 23 ++-- .../appsettings.json | 21 +++- .../authentication.db | Bin 4096 -> 0 bytes .../authentication.db-shm | Bin 32768 -> 0 bytes .../authentication.db-wal | Bin 119512 -> 0 bytes .../RegistrationOptionsTest.cs | 113 ++++++++++++++++++ 10 files changed, 161 insertions(+), 48 deletions(-) delete mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db delete mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db-shm delete mode 100644 Samples/RuntimeApps.Authentication.Sample/authentication.db-wal diff --git a/.gitignore b/.gitignore index 32d7bea..e63ca38 100644 --- a/.gitignore +++ b/.gitignore @@ -185,6 +185,9 @@ ClientBindist ~$* *~ *.dbmdl +Samples/RuntimeApps.Authentication.Sample/authentication.db +Samples/RuntimeApps.Authentication.Sample/authentication.db-shm +Samples/RuntimeApps.Authentication.Sample/authentication.db-wal *.dbproj.schemaview *.pfx *.publishsettings @@ -294,4 +297,4 @@ Thumbs.db #angular .angular/ -.angular/cache/ \ No newline at end of file +.angular/cache/ diff --git a/ReadMe.md b/ReadMe.md index 320f6e3..0bf0048 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -54,22 +54,12 @@ Add required services to DI: builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddRuntimeAppsAuthentication() .AddEfStores() - .UseJwt(JwtBearerDefaults.AuthenticationScheme, option => { - SymmetricSecurityKey signingKey = new(Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"])); - option.RequireHttpsMetadata = false; - option.SaveToken = true; - option.RefreshOnIssuerKeyNotFound = false; - option.TokenValidationParameters = new TokenValidationParameters { - ValidateIssuerSigningKey = true, - IssuerSigningKey = signingKey, - ValidateIssuer = false, - ValidIssuer = builder.Configuration["Jwt:Issuer"], - ValidateAudience = true, - ValidAudience = builder.Configuration["Jwt:Audience"], - ValidateLifetime = true, - ClockSkew = TimeSpan.Zero, - RequireExpirationTime = true, - }; + .UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, option => { + var signingKey = builder.Configuration["Authentication:Jwt:SigningKey"] + ?? throw new InvalidOperationException("Set Authentication:Jwt:SigningKey in user secrets or an environment variable."); + option.TokenValidationParameters.IssuerSigningKey = + new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)); + option.SaveToken = true; // Overrides Authentication:Jwt:SaveToken. }) .AddValidators(); ``` @@ -113,6 +103,8 @@ Option sections are `Authentication:Jwt` (the existing `JwtBearerOptions` type), .UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, options => options.RequireHttpsMetadata = true) ``` +The JWT overload binds `Authentication:Jwt` to the selected scheme only. For example, appsettings can hold `SaveToken`, `RefreshInterval`, and `TokenValidationParameters` (such as issuer and audience settings), while the callback can set an unbindable `IssuerSigningKey` from user secrets or an environment variable. Keep the signing key out of committed JSON. The callback overrides only the properties it assigns. + Actions alone remain supported. Defaults are supplied by each options type; configuration binding runs before callbacks; standard Options post-configuration runs afterward; feature validation runs on application startup. External provider options bind JSON values while callbacks can set non-bindable mapper delegates. Keep credentials in user secrets, environment variables, or a secret manager. Registrations use `TryAdd` to preserve application-provided services. Store interfaces for a single store implementation resolve the same scoped store instance. Use `AddUserMapper` to replace the selected mapper; register custom store interfaces before `AddStores` to retain your implementations. Repeating feature registration appends options configuration in call order and does not duplicate default provider/service registrations. diff --git a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs index 3be5dd9..61f4df3 100644 --- a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs +++ b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs @@ -82,10 +82,9 @@ private static RuntimeAppsAuthenticationBuilder AddForgotPas public static RuntimeAppsAuthenticationBuilder UseJwt(this RuntimeAppsAuthenticationBuilder builder, string scheme, Action configure) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configure); - builder.Services.TryAddScoped, JwtProvider>(); - builder.Services.Configure(configure); builder.Services.AddOptions(scheme).ValidateOnStart(); builder.Authentication.AddJwtBearer(scheme, configure); + AddJwtProvider(builder, scheme); return builder; } @@ -93,18 +92,20 @@ public static RuntimeAppsAuthenticationBuilder UseJwt, new() where TRole : IdentityRole where TKey : IEquatable { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configuration); const string section = "Authentication:Jwt"; - builder.Services.TryAddScoped, JwtProvider>(); builder.Authentication.AddJwtBearer(scheme); var schemeOptions = builder.Services.AddOptions(scheme).Bind(configuration.GetSection(section)); - builder.Services.Configure(configuration.GetSection(section)); - if (configure != null) { - builder.Services.Configure(configure); - builder.Services.Configure(scheme, configure); - } + if (configure != null) schemeOptions.Configure(configure); schemeOptions.ValidateOnStart(); + AddJwtProvider(builder, scheme); return builder; } + private static void AddJwtProvider(RuntimeAppsAuthenticationBuilder builder, string scheme) + where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable => + builder.Services.TryAddScoped>(services => new JwtProvider( + services.GetRequiredService>().Get(scheme), + services.GetRequiredService>())); + private static RuntimeAppsAuthenticationBuilder AddProvider(RuntimeAppsAuthenticationBuilder b, IConfiguration c, Action configure) where TUser : IdentityUser, new() where TRole : IdentityRole where TKey : IEquatable where TOption : BaseExternalLoginOption, new() where TProvider : class, IExternalLoginProvider { @@ -113,7 +114,7 @@ private static RuntimeAppsAuthenticationBuilder AddProvider< if (c != null) o.Bind(c.GetSection(TOptionSection.Name)); if (configure != null) o.Configure(configure); o.Validate(x => !string.IsNullOrWhiteSpace(x.ClientId) && !string.IsNullOrWhiteSpace(x.ClientSecret), "External login requires ClientId and ClientSecret.").ValidateOnStart(); - b.Services.TryAddTransient, TProvider>(); + b.Services.TryAddEnumerable(ServiceDescriptor.Transient, TProvider>()); b.Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); return b; } diff --git a/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs b/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs index b6126a8..746a7cf 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/JwtProvider.cs @@ -16,6 +16,10 @@ public JwtProvider(IOptions options, IUserClaimsPrincipalFacto _jwtOption = options.Value; _userClaimsPrincipalFactory = userClaimsPrincipalFactory; } + public JwtProvider(JwtBearerOptions options, IUserClaimsPrincipalFactory userClaimsPrincipalFactory) { + _jwtOption = options ?? throw new ArgumentNullException(nameof(options)); + _userClaimsPrincipalFactory = userClaimsPrincipalFactory ?? throw new ArgumentNullException(nameof(userClaimsPrincipalFactory)); + } public async Task GenerateTokenAsync(TUser user) { var credential = new SigningCredentials(_jwtOption.TokenValidationParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256); diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index c64186a..72ba48d 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -54,23 +54,14 @@ // Add default mapper between IdentityUser and IdentityUserDto .AddDefaultUserMapper>() //Add Jwt authentication serices to application - .UseJwt(JwtBearerDefaults.AuthenticationScheme, option => { - SymmetricSecurityKey signingKey = new(Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"])); - option.RequireHttpsMetadata = false; + .UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, option => { + var jwtSigningKey = builder.Configuration["Authentication:Jwt:SigningKey"] + ?? throw new InvalidOperationException("Configure Authentication:Jwt:SigningKey through user secrets or an environment variable."); + SymmetricSecurityKey signingKey = new(Encoding.ASCII.GetBytes(jwtSigningKey)); + // Overrides Authentication:Jwt:SaveToken while keeping the other bound values. option.SaveToken = true; - option.RefreshOnIssuerKeyNotFound = false; - option.RefreshInterval = TimeSpan.FromMinutes(int.Parse(builder.Configuration["Jwt:ExpireInMinute"])); - option.TokenValidationParameters = new TokenValidationParameters { - ValidateIssuerSigningKey = true, - IssuerSigningKey = signingKey, - ValidateIssuer = false, - ValidIssuer = builder.Configuration["Jwt:Issuer"], - ValidateAudience = true, - ValidAudience = builder.Configuration["Jwt:Audience"], - ValidateLifetime = true, - ClockSkew = TimeSpan.Zero, - RequireExpirationTime = true, - }; + option.RequireHttpsMetadata = false; + option.TokenValidationParameters.IssuerSigningKey = signingKey; }) //Add basic validations which is implemeted by ASP.Net core identity .AddValidators() diff --git a/Samples/RuntimeApps.Authentication.Sample/appsettings.json b/Samples/RuntimeApps.Authentication.Sample/appsettings.json index 772cd22..db297b7 100644 --- a/Samples/RuntimeApps.Authentication.Sample/appsettings.json +++ b/Samples/RuntimeApps.Authentication.Sample/appsettings.json @@ -6,16 +6,25 @@ } }, "AllowedHosts": "*", - "Jwt": { - "Key": "IdYpda-ZLkZcZ1txnXLEYTgEugmX6wBCi8dwcrXM_o0", - "Audience": "Runtime Apps Authentication Sample 1", - "Issuer": "Runtime Apps Authentication Sample 1", - "ExpireInMinute": 1000 - }, "ConnectionStrings": { "Authentication": "Data Source=authentication.db" }, "Authentication": { + "Jwt": { + "SaveToken": false, + "RequireHttpsMetadata": true, + "RefreshInterval": "00:16:40", + "TokenValidationParameters": { + "ValidateIssuerSigningKey": true, + "ValidateIssuer": false, + "ValidIssuer": "Runtime Apps Authentication Sample", + "ValidateAudience": true, + "ValidAudience": "Runtime Apps Authentication Sample", + "ValidateLifetime": true, + "ClockSkew": "00:00:00", + "RequireExpirationTime": true + } + }, "Verification": { "CodeLength": 7, "CodeLifetime": "00:10:00", diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db b/Samples/RuntimeApps.Authentication.Sample/authentication.db deleted file mode 100644 index cc04c103cdf5416b37dcbcd114b399f735eadcdf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmWFz^vNtqRY=P(%1ta$FlG>7U}9o$P*7lCU|@t|AVoG{WYC*>h8Lt=fNV2HHI9bB nXb6mkz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeDP#6LLQSS$G diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db-shm b/Samples/RuntimeApps.Authentication.Sample/authentication.db-shm deleted file mode 100644 index a26145014016ef99f886b7075070f14f2a1e545e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 32768 zcmeI*y-k~86b0Zf0m5$*2XJEkMo7mH=~#n;DiswYAR!ty@B&CkkupLG#0Km@ZSE;7 zQNAf?zV|uOk!;Jdt;hYjv*(|~G9QLva#Byyi|gBmr@!;d`Q!P`%b%<1@B6dG>92ox zv;Tbm^0V`qi#K`udLGwz44P%ZdJFdJJrwCFV(NrN%dQGx4Ku| zuTHDqt3Rr<>Ou9edQ?5G=JyBz0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK;XRuvU?yc0$H7qaS3Gc zLs|r~w<6;b$kvUt2xMtU#wC!ICutGL#+HmrAp2(0B9L`C8J9qo{iH=8yNWU{foxhz zi$E4dWn2Q*TwDLoZ0QPtJ_WKOEd=@$$bPyI=u;q<1B5`I0=bzX1o{-nwHP7Lr$Fu` z34uNZav@9z^eK?rctW60fn0?Y0(}bP9;y)NQy`asg+QMIxq&SN`V`3ZcWDuL1%a0? AZvX%Q diff --git a/Samples/RuntimeApps.Authentication.Sample/authentication.db-wal b/Samples/RuntimeApps.Authentication.Sample/authentication.db-wal deleted file mode 100644 index 1b307b93e8ab93ac7a6796598235f24647933f12..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 119512 zcmeI5e{36P8OLoWwbT6U+O=-G6>g4THEG7Cs_Le->OAL?nz)W*J6$6*c~|?|++yFk zzVq5_bR$ihtrQ_`3~56`2!T{U2vHDJDw;MyD}EKG!ZgN&5HN;-!Czw%Xqv|R-regv zpM7@R9}<|at0=zr=kt7?=lyX{-&fiBg#UzR^p6`oo;4o&IeTU9>31$XzW&hED;KtZ z?{J1BdF|l@6!A=L+|#yA9&i|*L}*j+`Y>;;hShw4Qc;l1a|lN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#d=>rlL~>BhxlDh8MkSTxBpXb2w!%lGinnp{Al!1|!ohLt)5pty^>q6carlXtT9W zZmrp2?c7pR+TK-_w&hy-u|uNqU_*^*1ygYPl~K2nZ*tMtDp9>Lr!P^uFIkyXW250v z_}VWh-qvs2fT`F{e^NskR~jvcF`fra(d(`#8rej&72Z+Q9f;k_Vy9*uR~+o8I~`do zxK31aQH+UaKXPhc)@#Kf6P96O^F+DpEhVE_+i1Tbcg1%1`GePT(-3!1MYTGjYHxtD zan#@jD9xhh_5Yjipzc|{vir&ATyDFBYNU|=+VtLcU2dWNpI#na+`Tyv%uae2AFQst z&F_e1jmsM#Dzk_p*!~d6&P5zR$C`z+=&8ejB)T`x%@U=)@=obOHeo009sH0T2KI z5C8!X009sHfjRe72?Rg@1V8`;KmY_l00ck) z1V8`;>IiJ4DJ(9qNp_*1V8`;KmY_l00ck)1V8`;KmY_fk-#lfDHa#FxbeYPo}YN>JmLbKXlm#L z0w4eaAOHd&00JNY0w4eaAOHe&1a74%EH3cG^!k@}UD diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs index 7ce9c14..b89bb31 100644 --- a/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationOptionsTest.cs @@ -1,9 +1,19 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; +using Moq; using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.ExternalLogin.Providers; +using RuntimeApps.Authentication.Features.PasswordRecovery.Contracts; +using RuntimeApps.Authentication.Features.PasswordRecovery.Models; +using RuntimeApps.Authentication.Features.RefreshTokens.Models; using RuntimeApps.Authentication.Features.Verification.Models; +using RuntimeApps.Authentication.Features.Account.Contracts; namespace RuntimeApps.Authentication.Test; @@ -31,6 +41,9 @@ public void CoreRegistration_DoesNotRegisterOptionalVerificationServices() { services.AddAuthentication().AddRuntimeAppsAuthentication(); using var provider = services.BuildServiceProvider(); Assert.False(provider.GetRequiredService().IsService(typeof(Features.Verification.Contracts.IVerificationWorkflowService))); + Assert.False(provider.GetRequiredService().IsService(typeof(IForgotPasswordService))); + Assert.False(provider.GetRequiredService().IsService(typeof(RuntimeApps.Authentication.Features.RefreshTokens.Contracts.IRefreshTokenService))); + Assert.Empty(provider.GetServices>()); } [Fact] @@ -41,4 +54,104 @@ public void InvalidVerificationOptions_FailOptionsValidation() { using var provider = services.BuildServiceProvider(); Assert.Throws(() => provider.GetRequiredService>().Value); } + + [Fact] + public void ExternalProviders_RegisterTogetherAndRepeatedCallsDoNotDuplicate() { + var services = new ServiceCollection(); + var builder = services.AddAuthentication().AddRuntimeAppsAuthentication(); + builder.AddGoogleExternalLogin(o => { o.ClientId = "google"; o.ClientSecret = "secret"; }); + builder.AddFacebookExternalLogin(o => { o.ClientId = "facebook"; o.ClientSecret = "secret"; }); + builder.AddMicrosoftExternalLogin(o => { o.ClientId = "microsoft"; o.ClientSecret = "secret"; }); + builder.AddGoogleExternalLogin(o => { o.ClientId = "google"; o.ClientSecret = "secret"; }); + using var provider = services.BuildServiceProvider(); + var providers = provider.GetServices>().ToArray(); + Assert.Equal(3, providers.Length); + Assert.Contains(providers, p => p is GoogleExternalLoginProvider); + Assert.Contains(providers, p => p is FacebookExternalLoginProvider); + Assert.Contains(providers, p => p is MicrosoftExternalLoginProvider); + } + + [Fact] + public void JwtOptions_AreIsolatedBySchemeForCodeAndConfiguration() { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + ["Authentication:Jwt:SaveToken"] = "true", + ["Authentication:Jwt:RequireHttpsMetadata"] = "false", + ["Authentication:Jwt:RefreshOnIssuerKeyNotFound"] = "true", + ["Authentication:Jwt:TokenValidationParameters:ValidAudience"] = "bound-audience" + }).Build(); + var services = new ServiceCollection(); + var builder = services.AddAuthentication().AddRuntimeAppsAuthentication(); + builder.UseJwt("configured", configuration, options => { options.SaveToken = false; options.RequireHttpsMetadata = true; }); + builder.UseJwt("code", options => { options.RequireHttpsMetadata = false; options.RefreshOnIssuerKeyNotFound = false; }); + + using var provider = services.BuildServiceProvider(); + var optionsMonitor = provider.GetRequiredService>(); + var configured = optionsMonitor.Get("configured"); + var code = optionsMonitor.Get("code"); + Assert.False(configured.SaveToken); + Assert.True(configured.RequireHttpsMetadata); + Assert.True(configured.RefreshOnIssuerKeyNotFound); + Assert.Equal("bound-audience", configured.TokenValidationParameters.ValidAudience); + Assert.True(code.SaveToken); + Assert.False(code.RefreshOnIssuerKeyNotFound); + Assert.False(code.RequireHttpsMetadata); + var defaults = optionsMonitor.Get(Options.DefaultName); + Assert.Null(defaults.TokenValidationParameters.ValidAudience); + Assert.True(defaults.RequireHttpsMetadata); + Assert.True(defaults.RefreshOnIssuerKeyNotFound); + } + + [Fact] + public void ForgotPasswordConfiguration_CanBeOverriddenInCode() { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + [$"{ForgotPasswordOptions.SectionName}:Method"] = "Link", + [$"{ForgotPasswordOptions.SectionName}:FrontendResetUrl"] = "https://example.test/reset" + }).Build(); + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .AddForgotPassword(configuration, options => options.Method = ForgotPasswordMethod.VerificationCode); + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + Assert.Equal(ForgotPasswordMethod.VerificationCode, options.Method); + Assert.Equal("https://example.test/reset", options.FrontendResetUrl); + } + + [Fact] + public void RefreshTokenConfiguration_CanBeOverriddenInCode() { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + [$"{RefreshTokenOptions.SectionName}:TokenLifetime"] = "10.00:00:00", + [$"{RefreshTokenOptions.SectionName}:RevokeFamilyOnReuse"] = "false", + [$"{RefreshTokenOptions.SectionName}:RefreshRequestsPerMinute"] = "41" + }).Build(); + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .AddRefreshToken(configuration, options => options.TokenLifetime = TimeSpan.FromDays(5)); + using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; + Assert.Equal(TimeSpan.FromDays(5), options.TokenLifetime); + Assert.False(options.RevokeFamilyOnReuse); + Assert.Equal(41, options.RefreshRequestsPerMinute); + } + + [Fact] + public async Task VerificationFeature_FailsStartupWithActionableMissingDependency() { + var services = new ServiceCollection(); + services.AddAuthentication().AddRuntimeAppsAuthentication() + .AddVerificationServices(); + using var provider = services.BuildServiceProvider(); + var validator = Assert.Single(provider.GetServices(), service => service.GetType().Name.StartsWith("VerificationDependenciesStartupValidator", StringComparison.Ordinal)); + var error = await Assert.ThrowsAsync(() => validator.StartAsync(CancellationToken.None)); + Assert.Contains("IVerificationRequestStore", error.Message); + Assert.Contains("AddVerificationRequestStore", error.Message); + } + + [Fact] + public void CoreRegistration_PreservesConsumerProvidedAccountService() { + var services = new ServiceCollection(); + var consumerService = new Mock>().Object; + services.AddSingleton(consumerService); + services.AddAuthentication().AddRuntimeAppsAuthentication(); + using var provider = services.BuildServiceProvider(); + Assert.Same(consumerService, provider.GetRequiredService>()); + } }