diff --git a/ReadMe.md b/ReadMe.md index 0bf0048..98cde67 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -28,6 +28,8 @@ Protect personal data | Protect personal user data in database by encrypt user d ## Getting Started +`IUserManager` provides user lookup, create, update, delete, and principal lookup operations. For services that need specific capabilities, inject focused contracts such as `IUserPasswordManager`, `IUserEmailManager`, `IUserRoleManager`, or `IUserClaimManager`. `AddRuntimeAppsAuthentication()` registers these contracts to the same scoped `RuntimeAppsUserManager` instance. The concrete manager remains customizable: derive from `RuntimeAppsUserManager` and register it with `.AddUserManager()` after calling `AddRuntimeAppsAuthentication`. A manager registered directly as `UserManager` before the builder must also derive from `RuntimeAppsUserManager` to share the focused interfaces. + To use this library do the steps: ### Install packages: diff --git a/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs index aece04c..077ae39 100644 --- a/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/DependencyInjection/RuntimeAppsAuthenticationBuilder.cs @@ -36,8 +36,9 @@ public RuntimeAppsAuthenticationBuilder AddAuthenticationSer Services.TryAddScoped>(); Services.TryAddScoped, UserClaimsPrincipalFactory>(); Services.TryAddScoped, DefaultUserConfirmation>(); - Services.TryAddScoped>(); - Services.TryAddScoped, RuntimeAppsUserManager>(); + AddUserManagerRegistration(); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + AddUserManagerInterfaces(); Services.TryAddScoped>(); Services.TryAddScoped, RuntimeAppsSignInManager>(); Services.TryAddScoped>(); @@ -51,6 +52,44 @@ public RuntimeAppsAuthenticationBuilder AddUserMapper), typeof(TMapper), lifetime)); return this; } + + /// Uses a derived RuntimeApps user manager as the shared Identity manager instance. + public RuntimeAppsAuthenticationBuilder AddUserManager() where TManager : RuntimeAppsUserManager { + Services.TryAddScoped(); + Services.Replace(ServiceDescriptor.Scoped>(sp => sp.GetRequiredService())); + Services.Replace(ServiceDescriptor.Scoped>(sp => sp.GetRequiredService>())); + Services.Replace(ServiceDescriptor.Scoped>(sp => sp.GetRequiredService>())); + AddUserManagerInterfaces(); + return this; + } + + private void AddUserManagerRegistration() { + var nativeManager = Services.LastOrDefault(descriptor => descriptor.ServiceType == typeof(UserManager)); + Services.TryAddScoped>(); + + if(nativeManager == null || nativeManager.ImplementationType == typeof(UserManager)) { + // Replace only Identity's default registration, or add our alias when none exists. + Services.Replace(ServiceDescriptor.Scoped>(sp => sp.GetRequiredService>())); + } else { + // Preserve an existing consumer registration. It must use the documented + // RuntimeAppsUserManager customization point for all abstractions to share it. + Services.Replace(ServiceDescriptor.Scoped>(sp => + sp.GetRequiredService>() as RuntimeAppsUserManager + ?? throw new InvalidOperationException($"The registered {typeof(UserManager).Name} must derive from {typeof(RuntimeAppsUserManager).Name}. Register a derived manager with AddUserManager() so focused interfaces and SignInManager share the same instance."))); + } + } + + private void AddUserManagerInterfaces() { + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + Services.TryAddScoped>(sp => sp.GetRequiredService>()); + } public RuntimeAppsAuthenticationBuilder AddUserMapper(Func toDto, Func toUser) where TUserDto : class { ArgumentNullException.ThrowIfNull(toDto); ArgumentNullException.ThrowIfNull(toUser); Services.Replace(ServiceDescriptor.Singleton>(new DelegateUserMapper(toDto, toUser))); diff --git a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs index 70edc21..bc867be 100644 --- a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs @@ -177,12 +177,12 @@ public static IEndpointRouteBuilder MapAccountApi(this IE return user != null ? mapper.ToDto(user) : null; }); - authorizedRouteGroup.MapPost("password/change", async Task> ([FromBody] ChangePasswordModel input, IUserManager userManager, HttpContext httpContext, IServiceProvider services) => { + authorizedRouteGroup.MapPost("password/change", async Task> ([FromBody] ChangePasswordModel input, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { var user = await userManager.GetUserAsync(httpContext.User); if(user == null) return ValidationProblemFactory.CreateValidationProblem("NoAccess", "Cannot change password without login"); - var result = await userManager.ChangePasswordAsync(user, input.CurrentPassword, input.NewPassword); + var result = await passwordManager.ChangePasswordAsync(user, input.CurrentPassword, input.NewPassword); if(!result.Succeeded) return result.CreateValidationProblem(); @@ -193,12 +193,12 @@ public static IEndpointRouteBuilder MapAccountApi(this IE return TypedResults.Ok(); }); - authorizedRouteGroup.MapPost("password", async Task> ([FromBody] string password, IUserManager userManager, HttpContext httpContext, IServiceProvider services) => { + authorizedRouteGroup.MapPost("password", async Task> ([FromBody] string password, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { var user = await userManager.GetUserAsync(httpContext.User); if(user == null) return ValidationProblemFactory.CreateValidationProblem("NoAccess", "Cannot change password without login"); - var result = await userManager.AddPasswordAsync(user, password); + var result = await passwordManager.AddPasswordAsync(user, password); if(!result.Succeeded) return result.CreateValidationProblem(); diff --git a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs index 4f515e9..fd47b47 100644 --- a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -24,6 +24,8 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi routes.MapPost("refresh", async Task (HttpContext context, IUserManager userManager, + IUserLockoutManager lockoutManager, + IUserLoginManager loginManager, ISignInManager signInManager, IRefreshTokenService refreshTokenService, IRefreshTokenRequestLimiter requestLimiter, @@ -56,8 +58,8 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi return Results.Unauthorized(); } - var isLockedOut = await userManager.IsLockedOutAsync(user); - var hasExternalLogin = (await userManager.GetLoginsAsync(user)).Count > 0; + var isLockedOut = await lockoutManager.IsLockedOutAsync(user); + var hasExternalLogin = (await loginManager.GetLoginsAsync(user)).Count > 0; var emailPolicyAllowsSignIn = user.EmailConfirmed || (hasExternalLogin && !verificationOptions.Value.RequireEmailVerificationForExternalLogins); if(isLockedOut || !emailPolicyAllowsSignIn || diff --git a/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs index 66ee0f9..16e01ec 100644 --- a/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs @@ -12,12 +12,12 @@ public static IEndpointRouteBuilder MapUserClaimGetApi(this IEndpointRout where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{userId}/claim", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager) => { + routeGroup.MapGet("{userId}/claim", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager, IUserClaimManager claimManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.GetClaimsAsync(user); + var result = await claimManager.GetClaimsAsync(user); return TypedResults.Ok(result?.Select(c => new ClaimDto(c))); }); @@ -27,45 +27,45 @@ public static IEndpointRouteBuilder MapUserClaimManageApi(this IEndpointR where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager) => { + routeGroup.MapPost("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.AddClaimAsync(user, claim.ToClaim()); + var result = await claimManager.AddClaimAsync(user, claim.ToClaim()); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapDelete("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager) => { + routeGroup.MapDelete("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.RemoveClaimAsync(user, claim.ToClaim()); + var result = await claimManager.RemoveClaimAsync(user, claim.ToClaim()); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapPost("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager) => { + routeGroup.MapPost("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager, IUserClaimManager claimManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.AddClaimsAsync(user, claims.Select(c => c.ToClaim())); + var result = await claimManager.AddClaimsAsync(user, claims.Select(c => c.ToClaim())); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapDelete("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager) => { + routeGroup.MapDelete("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager, IUserClaimManager claimManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.RemoveClaimsAsync(user, claims.Select(c => c.ToClaim())); + var result = await claimManager.RemoveClaimsAsync(user, claims.Select(c => c.ToClaim())); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); diff --git a/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs index f83dc3e..26637db 100644 --- a/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs @@ -11,12 +11,12 @@ public static IEndpointRouteBuilder MapUserRoleGetApi(this IEndpointRoute where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{userId}/Role", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager) => { + routeGroup.MapGet("{userId}/Role", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager, IUserRoleManager roleManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.GetRolesAsync(user); + var result = await roleManager.GetRolesAsync(user); return TypedResults.Ok(result); }); @@ -27,48 +27,48 @@ public static IEndpointRouteBuilder MapUserRoleManageApi(this IEndpointRo where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager) => { + routeGroup.MapPost("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager, IUserRoleManager roleManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.AddToRolesAsync(user, roles); + var result = await roleManager.AddToRolesAsync(user, roles); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapDelete("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager) => { + routeGroup.MapDelete("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager, IUserRoleManager roleManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.RemoveFromRolesAsync(user, roles); + var result = await roleManager.RemoveFromRolesAsync(user, roles); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapPost("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager) => { + routeGroup.MapPost("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.AddToRoleAsync(user, roleName); + var result = await roleManager.AddToRoleAsync(user, roleName); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(); }); - routeGroup.MapDelete("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager) => { + routeGroup.MapDelete("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager) => { var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await userManager.RemoveFromRoleAsync(user, roleName); + var result = await roleManager.RemoveFromRoleAsync(user, roleName); if(!result.Succeeded) return result.CreateValidationProblem(); diff --git a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs index f48d01a..01b85c9 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs @@ -15,6 +15,8 @@ public class UserAccountService: IUserAccountService where TUser : IdentityUser where TKey : IEquatable { private readonly IUserManager _userManager; + private readonly IUserLoginManager _loginManager; + private readonly IUserEmailManager _emailManager; private readonly ISignInManager _signInManager; private readonly IJwtProvider _jwtUtils; private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; @@ -39,7 +41,7 @@ public UserAccountService(IUserManager userManager, IJwtProvider jwtUtils = null) : this(userManager, signInManager, externalLoginProviders, authenticationHandlerProvider, contextAccessor, userClaimsPrincipalFactory, authenticationSchemeProvider, - jwtUtils, null, null, null, null, null) { + jwtUtils, null, null, null, null, null, null, null) { } public UserAccountService(IUserManager userManager, @@ -54,8 +56,12 @@ public UserAccountService(IUserManager userManager, IOptions refreshTokenOptions = null, IExternalLoginEmailTrustPolicy externalLoginEmailTrustPolicy = null, IOptions verificationOptions = null, - IVerificationWorkflowService verificationWorkflow = null) { + IVerificationWorkflowService verificationWorkflow = null, + IUserLoginManager loginManager = null, + IUserEmailManager emailManager = null) { _userManager = userManager; + _loginManager = loginManager ?? userManager as IUserLoginManager; + _emailManager = emailManager ?? userManager as IUserEmailManager; _signInManager = signInManager; _jwtUtils = jwtUtils; _externalLoginProviders = externalLoginProviders; @@ -80,12 +86,12 @@ public virtual async Task> ExternalLoginAsync(string provid return new Result(ResultCode.BadRequest, Result.CreateErrors("Invalid token", "Invalid External Authentication.")); var loginInfo = providerResult.LoginInfo; - var user = await _userManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); + var user = await _loginManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); if(user == null) { var trustedEmail = _externalLoginEmailTrustPolicy?.IsEmailTrusted(provider.Provider, providerResult) == true; var existingEmailUser = string.IsNullOrWhiteSpace(providerResult.Email) ? null - : await _userManager.FindByEmailAsync(providerResult.Email); + : await _emailManager.FindByEmailAsync(providerResult.Email); if(existingEmailUser != null) { // Never link an external identity to an existing account based on an unverified email. @@ -102,7 +108,7 @@ public virtual async Task> ExternalLoginAsync(string provid return new Result(ResultCode.BadRequest, updateResult.Errors); } - var addLoginResult = await _userManager.AddLoginAsync(user, loginInfo); + var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); } else { @@ -119,7 +125,7 @@ public virtual async Task> ExternalLoginAsync(string provid if(!createResult.Succeeded) return new Result(ResultCode.BadRequest, createResult.Errors); - var addLoginResult = await _userManager.AddLoginAsync(user, loginInfo); + var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); } diff --git a/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs b/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs index b7b046f..d50f5f2 100644 --- a/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs +++ b/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs @@ -12,7 +12,8 @@ namespace RuntimeApps.Authentication.Features.PasswordRecovery.Services { public sealed class ForgotPasswordService : IForgotPasswordService where TUser : IdentityUser where TKey : IEquatable { - private readonly IUserManager _userManager; + private readonly IUserEmailManager _emailManager; + private readonly IUserPasswordManager _passwordManager; private readonly UserManager _identityUserManager; private readonly IForgotPasswordVerificationWorkflow _verification; private readonly IRefreshTokenService _refreshTokens; @@ -21,14 +22,16 @@ public sealed class ForgotPasswordService : IForgotPasswordService< private readonly ForgotPasswordOptions _options; public ForgotPasswordService( - IUserManager userManager, + IUserEmailManager emailManager, + IUserPasswordManager passwordManager, UserManager identityUserManager, IForgotPasswordVerificationWorkflow verification, IEnumerable> passwordValidators, IServiceProvider services, ILogger> logger, IOptions options) { - _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); + _emailManager = emailManager ?? throw new ArgumentNullException(nameof(emailManager)); + _passwordManager = passwordManager ?? throw new ArgumentNullException(nameof(passwordManager)); _identityUserManager = identityUserManager ?? throw new ArgumentNullException(nameof(identityUserManager)); _verification = verification ?? throw new ArgumentNullException(nameof(verification)); _passwordValidators = passwordValidators ?? throw new ArgumentNullException(nameof(passwordValidators)); @@ -42,7 +45,7 @@ public async Task RequestAsync(string email, Cancellatio if(string.IsNullOrWhiteSpace(email) || email.Length > 256) return CreateGenericResponse(); - var user = await _userManager.FindByEmailAsync(email.Trim()); + var user = await _emailManager.FindByEmailAsync(email.Trim()); // Only a confirmed email address can be used to recover an account. if(user == null || !user.EmailConfirmed) return CreateGenericResponse(); @@ -102,14 +105,14 @@ public async Task ResetAsync( // user's security stamp. Code mode creates the Identity token after code validation. var resetToken = _options.Method == ForgotPasswordMethod.Link ? credential - : await _userManager.GeneratePasswordResetTokenAsync(user); + : await _passwordManager.GeneratePasswordResetTokenAsync(user); var verification = await _verification.VerifyAsync( verificationHandle, credential, VerificationPurpose.PasswordReset, VerificationChannel.Email, cancellationToken); if(!verification.Succeeded) return Failure("InvalidPasswordReset", "The password reset request is invalid."); - var resetResult = await _userManager.ResetPasswordAsync(verification.Data, resetToken, newPassword); + var resetResult = await _passwordManager.ResetPasswordAsync(verification.Data, resetToken, newPassword); if(!resetResult.Succeeded) return new Result(ResultCode.BadRequest, resetResult.Errors); diff --git a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs index a4bd9e3..c977657 100644 --- a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs +++ b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs @@ -13,6 +13,7 @@ public sealed class RegistrationService : IRegistrationService, new() where TKey : IEquatable { private readonly IUserManager _userManager; + private readonly IUserEmailManager _emailManager; private readonly IVerificationWorkflowService _verification; private readonly IUserAccountService _accountService; private readonly VerificationOptions _options; @@ -20,11 +21,13 @@ public sealed class RegistrationService : IRegistrationService userManager, + IUserEmailManager emailManager, IVerificationWorkflowService verification, IUserAccountService accountService, IOptions options, TimeProvider timeProvider = null) { _userManager = userManager; + _emailManager = emailManager; _verification = verification; _accountService = accountService; _options = options.Value; @@ -40,7 +43,7 @@ public async Task> RegisterAsync( if(string.IsNullOrWhiteSpace(user.UserName)) user.UserName = user.Email; - var existingUser = await _userManager.FindByEmailAsync(user.Email); + var existingUser = await _emailManager.FindByEmailAsync(user.Email); // Do not create or modify confirmed accounts. Keep the response indistinguishable // from a pending registration to avoid exposing whether an email is registered. if(existingUser?.EmailConfirmed == true) @@ -54,7 +57,7 @@ public async Task> RegisterAsync( var createResult = await _userManager.CreateAsync(user, password); if(!createResult.Succeeded) { // A concurrent registration may have created the account after our initial lookup. - var racedUser = await _userManager.FindByEmailAsync(user.Email); + var racedUser = await _emailManager.FindByEmailAsync(user.Email); if(racedUser?.EmailConfirmed == true) return GenericResponse(); if(racedUser == null) diff --git a/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs index baab00e..f647f93 100644 --- a/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs @@ -16,6 +16,7 @@ public sealed class VerificationWorkflowService : IForgotPasswordVe private readonly IVerificationCodeVerifier _verifier; private readonly IVerificationSender _sender; private readonly IUserManager _userManager; + private readonly IUserPasswordManager _passwordManager; private readonly ILookupNormalizer _normalizer; private readonly VerificationOptions _options; private readonly ForgotPasswordOptions _forgotOptions; @@ -28,10 +29,11 @@ public VerificationWorkflowService( IVerificationCodeVerifier verifier, IVerificationSender sender, IUserManager userManager, + IUserPasswordManager passwordManager, ILookupNormalizer normalizer, IOptions options, TimeProvider timeProvider = null) - : this(store, generator, verifier, sender, userManager, normalizer, options, + : this(store, generator, verifier, sender, userManager, passwordManager, normalizer, options, Options.Create(new ForgotPasswordOptions()), timeProvider) { } @@ -41,6 +43,7 @@ public VerificationWorkflowService( IVerificationCodeVerifier verifier, IVerificationSender sender, IUserManager userManager, + IUserPasswordManager passwordManager, ILookupNormalizer normalizer, IOptions options, IOptions forgotOptions, @@ -50,6 +53,7 @@ public VerificationWorkflowService( _verifier = verifier ?? throw new ArgumentNullException(nameof(verifier)); _sender = sender ?? throw new ArgumentNullException(nameof(sender)); _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); + _passwordManager = passwordManager ?? throw new ArgumentNullException(nameof(passwordManager)); _normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer)); _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _forgotOptions = forgotOptions?.Value ?? throw new ArgumentNullException(nameof(forgotOptions)); @@ -195,7 +199,7 @@ await _store.TryIncrementFailedAttemptsAsync(request.Id, request.CodeVersion, private async Task CreateCredentialAsync( TUser user, VerificationRequest request, string handle, CancellationToken cancellationToken) { if(request.Purpose == VerificationPurpose.PasswordReset && _forgotOptions.Method == ForgotPasswordMethod.Link) - return await _userManager.GeneratePasswordResetTokenAsync(user); + return await _passwordManager.GeneratePasswordResetTokenAsync(user); return await _generator.GenerateAsync( CreateContext(user, request, handle, null), _options, cancellationToken); } diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs new file mode 100644 index 0000000..74a8052 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs @@ -0,0 +1,14 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserClaimManager where TUser : class { + Task AddClaimAsync(TUser user, Claim claim); + Task AddClaimsAsync(TUser user, IEnumerable claims); + Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim); + Task RemoveClaimAsync(TUser user, Claim claim); + Task RemoveClaimsAsync(TUser user, IEnumerable claims); + Task> GetClaimsAsync(TUser user); + Task> GetUsersForClaimAsync(Claim claim); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserEmailManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserEmailManager.cs new file mode 100644 index 0000000..99c343e --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserEmailManager.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserEmailManager where TUser : class { + Task FindByEmailAsync(string email); + Task SetEmailAsync(TUser user, string email); + Task GenerateEmailConfirmationTokenAsync(TUser user); + Task ConfirmEmailAsync(TUser user, string token); + Task GenerateChangeEmailTokenAsync(TUser user, string newEmail); + Task ChangeEmailAsync(TUser user, string newEmail, string token); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserLockoutManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserLockoutManager.cs new file mode 100644 index 0000000..906c4e1 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserLockoutManager.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserLockoutManager where TUser : class { + Task IsLockedOutAsync(TUser user); + Task SetLockoutEnabledAsync(TUser user, bool enabled); + Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd); + Task AccessFailedAsync(TUser user); + Task ResetAccessFailedCountAsync(TUser user); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserLoginManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserLoginManager.cs new file mode 100644 index 0000000..14ed505 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserLoginManager.cs @@ -0,0 +1,10 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserLoginManager where TUser : class { + Task FindByLoginAsync(string loginProvider, string providerKey); + Task AddLoginAsync(TUser user, UserLoginInfo login); + Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey); + Task> GetLoginsAsync(TUser user); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs index 1dd96c0..0dcf7e6 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs @@ -2,73 +2,13 @@ using Microsoft.AspNetCore.Identity; namespace RuntimeApps.Authentication.Identity.Contracts { - public interface IUserManager - where TUser : class { - string GetUserName(ClaimsPrincipal principal); - string GetUserId(ClaimsPrincipal principal); + public interface IUserManager where TUser : class { Task GetUserAsync(ClaimsPrincipal principal); - - Task CreateAsync(TUser user); Task CreateAsync(TUser user, string password); Task UpdateAsync(TUser user); Task DeleteAsync(TUser user); Task FindByIdAsync(string userId); Task FindByNameAsync(string userName); - - Task CheckPasswordAsync(TUser user, string password); - Task AddPasswordAsync(TUser user, string password); - Task ChangePasswordAsync(TUser user, string currentPassword, string newPassword); - Task RemovePasswordAsync(TUser user); - Task GeneratePasswordResetTokenAsync(TUser user); - Task ResetPasswordAsync(TUser user, string token, string newPassword); - - Task FindByLoginAsync(string loginProvider, string providerKey); - Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey); - Task AddLoginAsync(TUser user, UserLoginInfo login); - Task> GetLoginsAsync(TUser user); - - Task AddClaimAsync(TUser user, Claim claim); - Task AddClaimsAsync(TUser user, IEnumerable claims); - Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim); - Task RemoveClaimAsync(TUser user, Claim claim); - Task RemoveClaimsAsync(TUser user, IEnumerable claims); - Task> GetClaimsAsync(TUser user); - - Task AddToRoleAsync(TUser user, string role); - Task AddToRolesAsync(TUser user, IEnumerable roles); - Task RemoveFromRoleAsync(TUser user, string role); - Task RemoveFromRolesAsync(TUser user, IEnumerable roles); - Task> GetRolesAsync(TUser user); - Task IsInRoleAsync(TUser user, string role); - - Task SetEmailAsync(TUser user, string email); - Task FindByEmailAsync(string email); - Task GenerateEmailConfirmationTokenAsync(TUser user); - Task ConfirmEmailAsync(TUser user, string token); - Task GenerateChangeEmailTokenAsync(TUser user, string newEmail); - Task ChangeEmailAsync(TUser user, string newEmail, string token); - - Task SetPhoneNumberAsync(TUser user, string phoneNumber); - Task ChangePhoneNumberAsync(TUser user, string phoneNumber, string token); - Task GenerateChangePhoneNumberTokenAsync(TUser user, string phoneNumber); - - void RegisterTokenProvider(string providerName, IUserTwoFactorTokenProvider provider); - Task> GetValidTwoFactorProvidersAsync(TUser user); - Task VerifyTwoFactorTokenAsync(TUser user, string tokenProvider, string token); - Task GenerateTwoFactorTokenAsync(TUser user, string tokenProvider); - Task SetTwoFactorEnabledAsync(TUser user, bool enabled); - Task IsLockedOutAsync(TUser user); - Task SetLockoutEnabledAsync(TUser user, bool enabled); - Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd); - Task AccessFailedAsync(TUser user); - Task ResetAccessFailedCountAsync(TUser user); - Task> GetUsersForClaimAsync(Claim claim); - Task> GetUsersInRoleAsync(string roleName); - Task GetAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName); - Task SetAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName, string tokenValue); - Task RemoveAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName); - Task GetAuthenticatorKeyAsync(TUser user); - Task ResetAuthenticatorKeyAsync(TUser user); } } diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs new file mode 100644 index 0000000..d0259b8 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserPasswordManager where TUser : class { + Task CheckPasswordAsync(TUser user, string password); + Task AddPasswordAsync(TUser user, string password); + Task ChangePasswordAsync(TUser user, string currentPassword, string newPassword); + Task RemovePasswordAsync(TUser user); + Task GeneratePasswordResetTokenAsync(TUser user); + Task ResetPasswordAsync(TUser user, string token, string newPassword); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserPhoneNumberManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserPhoneNumberManager.cs new file mode 100644 index 0000000..475dce6 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserPhoneNumberManager.cs @@ -0,0 +1,9 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserPhoneNumberManager where TUser : class { + Task SetPhoneNumberAsync(TUser user, string phoneNumber); + Task ChangePhoneNumberAsync(TUser user, string phoneNumber, string token); + Task GenerateChangePhoneNumberTokenAsync(TUser user, string phoneNumber); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs new file mode 100644 index 0000000..e699037 --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserRoleManager where TUser : class { + Task AddToRoleAsync(TUser user, string role); + Task AddToRolesAsync(TUser user, IEnumerable roles); + Task RemoveFromRoleAsync(TUser user, string role); + Task RemoveFromRolesAsync(TUser user, IEnumerable roles); + Task> GetRolesAsync(TUser user); + Task IsInRoleAsync(TUser user, string role); + Task> GetUsersInRoleAsync(string roleName); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserTokenManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserTokenManager.cs new file mode 100644 index 0000000..a594b1a --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserTokenManager.cs @@ -0,0 +1,10 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserTokenManager where TUser : class { + Task GetAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName); + Task SetAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName, string tokenValue); + Task RemoveAuthenticationTokenAsync(TUser user, string loginProvider, string tokenName); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserTwoFactorManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserTwoFactorManager.cs new file mode 100644 index 0000000..c3ca58f --- /dev/null +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserTwoFactorManager.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Identity.Contracts { + public interface IUserTwoFactorManager where TUser : class { + void RegisterTokenProvider(string providerName, IUserTwoFactorTokenProvider provider); + Task> GetValidTwoFactorProvidersAsync(TUser user); + Task VerifyTwoFactorTokenAsync(TUser user, string tokenProvider, string token); + Task GenerateTwoFactorTokenAsync(TUser user, string tokenProvider); + Task SetTwoFactorEnabledAsync(TUser user, bool enabled); + Task GetAuthenticatorKeyAsync(TUser user); + Task ResetAuthenticatorKeyAsync(TUser user); + } +} diff --git a/RuntimeApps.Authentication/Identity/RuntimeAppsUserManager.cs b/RuntimeApps.Authentication/Identity/RuntimeAppsUserManager.cs index f0ab0f0..ebac6a4 100644 --- a/RuntimeApps.Authentication/Identity/RuntimeAppsUserManager.cs +++ b/RuntimeApps.Authentication/Identity/RuntimeAppsUserManager.cs @@ -3,7 +3,11 @@ using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Identity.Contracts; namespace RuntimeApps.Authentication.Identity { - public class RuntimeAppsUserManager: UserManager, IUserManager + public class RuntimeAppsUserManager: UserManager, + IUserManager, IUserPasswordManager, IUserEmailManager, + IUserPhoneNumberManager, IUserLoginManager, IUserClaimManager, + IUserRoleManager, IUserTwoFactorManager, IUserLockoutManager, + IUserTokenManager where TUser : class { public RuntimeAppsUserManager(IUserStore store, IOptions optionsAccessor, diff --git a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/DbInitializer.cs b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/DbInitializer.cs index 2d8a09a..5a1d9c2 100644 --- a/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/DbInitializer.cs +++ b/Samples/RuntimeApps.Authentication.Sample.ClaimAuthorize/DbInitializer.cs @@ -10,7 +10,7 @@ using RuntimeApps.Authentication.Identity.Contracts; namespace RuntimeApps.Authentication.Sample.ClaimAuthorize { public class DbInitializer { - public static void Initialize(ApplicationDbContext context, IUserManager> userManager, IRoleManager> roleManager) { + public static void Initialize(ApplicationDbContext context, IUserManager> userManager, IUserRoleManager> userRoleManager, IRoleManager> roleManager) { context.Database.Migrate(); if(context.Users.Any()) { @@ -28,7 +28,7 @@ public static void Initialize(ApplicationDbContext context, IUserManager(); var userManager = services.GetRequiredService>>(); + var userRoleManager = services.GetRequiredService>>(); var roleManager = services.GetRequiredService>>(); - DbInitializer.Initialize(dbContext, userManager, roleManager); + DbInitializer.Initialize(dbContext, userManager, userRoleManager, roleManager); } catch(Exception ex) { var logger = services.GetRequiredService>(); logger.LogError(ex, "An error occurred while seeding the database."); diff --git a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/DbInitializer.cs b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/DbInitializer.cs index 3fa9f09..07875da 100644 --- a/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/DbInitializer.cs +++ b/Samples/RuntimeApps.Authentication.Sample.RoleAuthorize/DbInitializer.cs @@ -9,7 +9,7 @@ using RuntimeApps.Authentication.Identity.Contracts; namespace RuntimeApps.Authentication.Sample.RoleAuthorize { public static class DbInitializer { - public static void Initialize(ApplicationDbContext context, IUserManager> userManager, IRoleManager> roleManager) { + public static void Initialize(ApplicationDbContext context, IUserManager> userManager, IUserRoleManager> userRoleManager, IRoleManager> roleManager) { context.Database.Migrate(); if(context.Users.Any()) { @@ -26,7 +26,7 @@ public static void Initialize(ApplicationDbContext context, IUserManager(); var userManager = services.GetRequiredService>>(); + var userRoleManager = services.GetRequiredService>>(); var roleManager = services.GetRequiredService>>(); - DbInitializer.Initialize(dbContext, userManager, roleManager); + DbInitializer.Initialize(dbContext, userManager, userRoleManager, roleManager); } catch(Exception ex) { var logger = services.GetRequiredService>(); logger.LogError(ex, "An error occurred while seeding the database."); diff --git a/Tests/RuntimeApps.Authentication.Test/ForgotPasswordServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/ForgotPasswordServiceTest.cs index 22f4c75..5fdbac7 100644 --- a/Tests/RuntimeApps.Authentication.Test/ForgotPasswordServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/ForgotPasswordServiceTest.cs @@ -32,12 +32,12 @@ namespace RuntimeApps.Authentication.Test { public class ForgotPasswordServiceTest { [Fact] public async Task Request_UnknownEmail_ReturnsGenericResponseWithNonexistentHandle() { - var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); - userManager.Setup(manager => manager.FindByEmailAsync("missing@example.com")) + emailManager.Setup(manager => manager.FindByEmailAsync("missing@example.com")) .ReturnsAsync((IdentityUser)null); - var service = CreateService(userManager, workflow); + var service = CreateService(emailManager, workflow); var response = await service.RequestAsync("missing@example.com"); Assert.False(string.IsNullOrWhiteSpace(response.VerificationHandle)); @@ -49,19 +49,19 @@ public async Task Request_UnknownEmail_ReturnsGenericResponseWithNonexistentHand [Fact] public async Task Request_ConfirmedEmail_ReturnsStartedVerificationHandle() { - var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var user = new IdentityUser { Email = "person@example.com", EmailConfirmed = true }; - userManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); workflow.Setup(service => service.StartAsync( user, VerificationPurpose.PasswordReset, VerificationChannel.Email, user.Email, null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("real-handle", DateTimeOffset.UtcNow.AddMinutes(10))); - var service = CreateService(userManager, workflow); + var service = CreateService(emailManager, workflow); var response = await service.RequestAsync(user.Email); Assert.Equal("real-handle", response.VerificationHandle); @@ -72,15 +72,15 @@ public async Task Request_ConfirmedEmail_ReturnsStartedVerificationHandle() { [Fact] public async Task Request_UnconfirmedEmail_DoesNotStartVerification() { - var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var user = new IdentityUser { Email = "unconfirmed@example.com", EmailConfirmed = false }; - userManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); - var service = CreateService(userManager, workflow); + var service = CreateService(emailManager, workflow); var response = await service.RequestAsync(user.Email); Assert.False(string.IsNullOrWhiteSpace(response.VerificationHandle)); @@ -91,19 +91,19 @@ public async Task Request_UnconfirmedEmail_DoesNotStartVerification() { [Fact] public async Task Request_ConfirmedEmailInLinkMode_DoesNotReturnVerificationHandle() { - var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var user = new IdentityUser { Email = "person@example.com", EmailConfirmed = true }; - userManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); workflow.Setup(service => service.StartAsync( user, VerificationPurpose.PasswordReset, VerificationChannel.Email, user.Email, null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("real-handle", DateTimeOffset.UtcNow.AddMinutes(10))); - var service = CreateService(userManager, workflow, ForgotPasswordMethod.Link); + var service = CreateService(emailManager, workflow, ForgotPasswordMethod.Link); var response = await service.RequestAsync(user.Email); Assert.Null(response.VerificationHandle); @@ -113,7 +113,7 @@ public async Task Request_ConfirmedEmailInLinkMode_DoesNotReturnVerificationHand } private static ForgotPasswordService CreateService( - Mock> userManager, + Mock> emailManager, Mock> workflow, ForgotPasswordMethod method = ForgotPasswordMethod.VerificationCode) { var store = new Mock>(); @@ -129,7 +129,8 @@ private static ForgotPasswordService CreateService( NullLogger>.Instance); return new ForgotPasswordService( - userManager.Object, + emailManager.Object, + Mock.Of>(), identityManager, workflow.Object, Array.Empty>(), @@ -143,4 +144,4 @@ private static ForgotPasswordService CreateService( })); } } -} \ No newline at end of file +} diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs index da07a9b..a4cd26a 100644 --- a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs @@ -29,19 +29,20 @@ public class RegistrationServiceTest { [Fact] public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() { var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); - userManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); userManager.Setup(manager => manager.CreateAsync(user, "StrongPassword!1")).ReturnsAsync(IdentityResult.Success); workflow.Setup(service => service.StartAsync( user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("opaque-handle", expiresAt)); - var service = CreateService(userManager, workflow, account); + var service = CreateService(userManager, emailManager, workflow, account); var result = await service.RegisterAsync(user, "StrongPassword!1"); Assert.True(result.Succeeded); @@ -54,19 +55,20 @@ public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() [Fact] public async Task Register_ExistingPendingUser_ReusesAccountWithoutUpdatingIt() { var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var existing = new IdentityUser { Email = "pending@example.com", UserName = "old-name" }; var requested = new IdentityUser { Email = existing.Email, UserName = "new-name" }; var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); - userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); + emailManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); workflow.Setup(service => service.StartAsync( existing, VerificationPurpose.Registration, VerificationChannel.Email, existing.Email, null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("new-handle", expiresAt)); - var service = CreateService(userManager, workflow, account); + var service = CreateService(userManager, emailManager, workflow, account); var result = await service.RegisterAsync(requested, "AttackerSuppliedPassword!"); Assert.True(result.Succeeded); @@ -78,12 +80,13 @@ public async Task Register_ExistingPendingUser_ReusesAccountWithoutUpdatingIt() [Fact] public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSending() { var userManager = new Mock>(); + var emailManager = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var existing = new IdentityUser { Email = "confirmed@example.com", EmailConfirmed = true }; - userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); + emailManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); - var service = CreateService(userManager, workflow, account); + var service = CreateService(userManager, emailManager, workflow, account); var result = await service.RegisterAsync(new IdentityUser { Email = existing.Email }, "Password!"); Assert.True(result.Succeeded); @@ -95,9 +98,10 @@ public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSe private static RegistrationService CreateService( Mock> userManager, + Mock> emailManager, Mock> workflow, Mock> account) => - new(userManager.Object, workflow.Object, account.Object, + new(userManager.Object, emailManager.Object, workflow.Object, account.Object, Options.Create(new VerificationOptions())); } -} \ No newline at end of file +} diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index badd6f2..5326dfe 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -1,4 +1,4 @@ -using FluentAssertions; +using FluentAssertions; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; @@ -22,6 +22,8 @@ namespace RuntimeApps.Authentication.Test { public class UserAccountServiceTest { private const IdentityUser nullUSer = null; private readonly Mock> _userManagerMock; + private readonly Mock> _loginManagerMock; + private readonly Mock> _emailManagerMock; private readonly Mock> _signInManagerMock; private readonly Mock> _jwtProviderMock; private readonly Mock> _externalLoginProvider1; @@ -35,6 +37,8 @@ public class UserAccountServiceTest { public UserAccountServiceTest() { _userManagerMock = new Mock>(); + _loginManagerMock = new Mock>(); + _emailManagerMock = new Mock>(); _signInManagerMock = new Mock>(); _jwtProviderMock = new Mock>(); _externalLoginProvider1 = new Mock>(); @@ -52,7 +56,7 @@ public UserAccountServiceTest() { _httpContextAccessorMock.Object, _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, - _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object); + _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object, null, null, _loginManagerMock.Object, _emailManagerMock.Object); _authenticationSchemeProviderMock.Setup(p => p.GetDefaultSignInSchemeAsync()) .ReturnsAsync((AuthenticationScheme)null); @@ -187,13 +191,13 @@ public async Task ExternalLogin_Success_CreateNewUser() { .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false }); - _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) + _loginManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(nullUSer); - _userManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) + _emailManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) .ReturnsAsync(nullUSer); _userManagerMock.Setup(u => u.CreateAsync(user)) .ReturnsAsync(IdentityResult.Success); - _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) + _loginManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) .ReturnsAsync(IdentityResult.Success); _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) .ReturnsAsync(appToken); @@ -208,7 +212,7 @@ public async Task ExternalLogin_Success_CreateNewUser() { result.Meta.Should().NotBeNull() .And.Be(appToken); _userManagerMock.Verify(u => u.CreateAsync(It.IsAny()), Times.Once()); - _userManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Once()); + _loginManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Once()); } [Fact] @@ -226,14 +230,14 @@ public async Task ExternalLogin_ExistingEmail_DoesNotAutomaticallyLink() { Email = existingUser.Email, EmailVerified = true }); - _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - _userManagerMock.Setup(manager => manager.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); + _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _emailManagerMock.Setup(manager => manager.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); var result = await _userAccountService.ExternalLoginAsync(provider, token); Assert.False(result.Succeeded); Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict, result.Code); - _userManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); + _loginManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } [Fact] @@ -249,14 +253,14 @@ public async Task ExternalLogin_UnverifiedEmail_DoesNotLinkExistingAccount() { User = new IdentityUser { Email = user.Email }, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false }); - _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - _userManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _emailManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); var result = await _userAccountService.ExternalLoginAsync(provider, token); Assert.False(result.Succeeded); Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict, result.Code); - _userManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); + _loginManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } [Fact] @@ -274,10 +278,10 @@ public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false }); - _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - _userManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _emailManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); _userManagerMock.Setup(manager => manager.CreateAsync(user)).ReturnsAsync(IdentityResult.Success); - _userManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); + _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); workflow.Setup(service => service.StartAsync( user, RuntimeApps.Authentication.Features.Verification.Models.VerificationPurpose.Registration, RuntimeApps.Authentication.Features.Verification.Models.VerificationChannel.Email, user.Email, @@ -292,7 +296,7 @@ public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object, Microsoft.Extensions.Options.Options.Create(new RuntimeApps.Authentication.Features.Verification.Models.VerificationOptions { RequireEmailVerificationForExternalLogins = true - }), workflow.Object); + }), workflow.Object, _loginManagerMock.Object, _emailManagerMock.Object); var result = await service.ExternalLoginAsync(provider, token); @@ -323,9 +327,9 @@ public async Task ExternalLogin_Success_ExistsLogin() { .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false }); - _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) + _loginManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(user); - _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) + _loginManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) .ReturnsAsync(IdentityResult.Success); _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) .ReturnsAsync(appToken); @@ -340,7 +344,7 @@ public async Task ExternalLogin_Success_ExistsLogin() { result.Meta.Should().NotBeNull() .And.Be(appToken); _userManagerMock.Verify(u => u.CreateAsync(It.IsAny()), Times.Never()); - _userManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); + _loginManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } @@ -362,7 +366,7 @@ public async Task ExternalLogin_ProviderNotFound() { result.Data.Should().BeNull(); result.Meta.Should().BeNull(); _userManagerMock.Verify(u => u.CreateAsync(It.IsAny()), Times.Never()); - _userManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); + _loginManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } } } diff --git a/Tests/RuntimeApps.Authentication.Test/UserManagerDependencyInjectionTest.cs b/Tests/RuntimeApps.Authentication.Test/UserManagerDependencyInjectionTest.cs new file mode 100644 index 0000000..50a8e9d --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/UserManagerDependencyInjectionTest.cs @@ -0,0 +1,115 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using RuntimeApps.Authentication.DependencyInjection; +using RuntimeApps.Authentication.Identity; +using RuntimeApps.Authentication.Identity.Contracts; + +namespace RuntimeApps.Authentication.Test { + public class UserManagerDependencyInjectionTest { + [Fact] + public void Managers_AreSharedWithinScope_AndScopedAcrossScopes() { + using var provider = CreateServices().BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + using var firstScope = provider.CreateScope(); + using var secondScope = provider.CreateScope(); + + var manager = firstScope.ServiceProvider.GetRequiredService>(); + AssertManagerAliases(firstScope.ServiceProvider, manager); + Assert.Same(manager, firstScope.ServiceProvider.GetRequiredService>()); + + var secondManager = secondScope.ServiceProvider.GetRequiredService>(); + Assert.NotSame(manager, secondManager); + AssertManagerAliases(secondScope.ServiceProvider, secondManager); + } + + [Fact] + public void ConsumerRegisteredDerivedNativeManager_IsPreservedAndShared() { + var services = new ServiceCollection(); + AddStore(services); + services.AddScoped(); + services.AddScoped>(sp => sp.GetRequiredService()); + services.AddAuthentication().AddRuntimeAppsAuthentication(); + + using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + using var scope = provider.CreateScope(); + var customManager = scope.ServiceProvider.GetRequiredService(); + + AssertManagerAliases(scope.ServiceProvider, customManager); + Assert.Same(customManager, scope.ServiceProvider.GetRequiredService()); + } + + [Fact] + public void IdentityCoreDefaultManager_IsAliasedToRuntimeAppsManager() { + var services = new ServiceCollection(); + AddStore(services); + services.AddIdentityCore(); + services.AddAuthentication().AddRuntimeAppsAuthentication(); + + using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + using var scope = provider.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService>(); + + AssertManagerAliases(scope.ServiceProvider, manager); + } + + [Fact] + public void AddUserManager_UsesDerivedManagerForAllRegistrations() { + var services = CreateServices(); + var builder = services.AddAuthentication().AddRuntimeAppsAuthentication(); + builder.AddUserManager(); + + using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + using var scope = provider.CreateScope(); + var customManager = scope.ServiceProvider.GetRequiredService(); + + AssertManagerAliases(scope.ServiceProvider, customManager); + } + + private static ServiceCollection CreateServices() { + var services = new ServiceCollection(); + AddStore(services); + services.AddAuthentication().AddRuntimeAppsAuthentication(); + return services; + } + + private static void AddStore(IServiceCollection services) { + services.AddSingleton>(Mock.Of>()); + services.AddSingleton>(Mock.Of>()); + } + + private static void AssertManagerAliases(IServiceProvider services, RuntimeAppsUserManager manager) { + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>()); + Assert.Same(manager, services.GetRequiredService>().UserManager); + } + + public sealed class CustomUserManager : RuntimeAppsUserManager { + public CustomUserManager( + IUserStore store, + IOptions optionsAccessor, + IPasswordHasher passwordHasher, + IEnumerable> userValidators, + IEnumerable> passwordValidators, + ILookupNormalizer keyNormalizer, + IdentityErrorDescriber errors, + IServiceProvider services, + ILogger> logger) + : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, + keyNormalizer, errors, services, logger) { + } + } + } +}