Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Protect personal data | Protect personal user data in database by encrypt user d

## Getting Started

`IUserManager<TUser>` provides user lookup, create, update, delete, and principal lookup operations. For services that need specific capabilities, inject focused contracts such as `IUserPasswordManager<TUser>`, `IUserEmailManager<TUser>`, `IUserRoleManager<TUser>`, or `IUserClaimManager<TUser>`. `AddRuntimeAppsAuthentication<TUser, TRole, TKey>()` registers these contracts to the same scoped `RuntimeAppsUserManager<TUser>` instance. The concrete manager remains customizable: derive from `RuntimeAppsUserManager<TUser>` and register it with `.AddUserManager<YourUserManager>()` after calling `AddRuntimeAppsAuthentication`. A manager registered directly as `UserManager<TUser>` before the builder must also derive from `RuntimeAppsUserManager<TUser>` to share the focused interfaces.

To use this library do the steps:

### Install packages:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ public RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddAuthenticationSer
Services.TryAddScoped<ITwoFactorSecurityStampValidator, TwoFactorSecurityStampValidator<TUser>>();
Services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
Services.TryAddScoped<IUserConfirmation<TUser>, DefaultUserConfirmation<TUser>>();
Services.TryAddScoped<UserManager<TUser>>();
Services.TryAddScoped<IUserManager<TUser>, RuntimeAppsUserManager<TUser>>();
AddUserManagerRegistration();
Services.TryAddScoped<IUserManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
AddUserManagerInterfaces();
Services.TryAddScoped<SignInManager<TUser>>();
Services.TryAddScoped<ISignInManager<TUser>, RuntimeAppsSignInManager<TUser>>();
Services.TryAddScoped<RoleManager<TRole>>();
Expand All @@ -51,6 +52,44 @@ public RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddUserMapper<TUserD
Services.Replace(ServiceDescriptor.Describe(typeof(IUserMapper<TUser, TUserDto>), typeof(TMapper), lifetime));
return this;
}

/// <summary>Uses a derived RuntimeApps user manager as the shared Identity manager instance.</summary>
public RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddUserManager<TManager>() where TManager : RuntimeAppsUserManager<TUser> {
Services.TryAddScoped<TManager>();
Services.Replace(ServiceDescriptor.Scoped<RuntimeAppsUserManager<TUser>>(sp => sp.GetRequiredService<TManager>()));
Services.Replace(ServiceDescriptor.Scoped<UserManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>()));
Services.Replace(ServiceDescriptor.Scoped<IUserManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>()));
AddUserManagerInterfaces();
return this;
}

private void AddUserManagerRegistration() {
var nativeManager = Services.LastOrDefault(descriptor => descriptor.ServiceType == typeof(UserManager<TUser>));
Services.TryAddScoped<RuntimeAppsUserManager<TUser>>();

if(nativeManager == null || nativeManager.ImplementationType == typeof(UserManager<TUser>)) {
// Replace only Identity's default registration, or add our alias when none exists.
Services.Replace(ServiceDescriptor.Scoped<UserManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>()));
} else {
// Preserve an existing consumer registration. It must use the documented
// RuntimeAppsUserManager customization point for all abstractions to share it.
Services.Replace(ServiceDescriptor.Scoped<RuntimeAppsUserManager<TUser>>(sp =>
sp.GetRequiredService<UserManager<TUser>>() as RuntimeAppsUserManager<TUser>
?? throw new InvalidOperationException($"The registered {typeof(UserManager<TUser>).Name} must derive from {typeof(RuntimeAppsUserManager<TUser>).Name}. Register a derived manager with AddUserManager<TManager>() so focused interfaces and SignInManager share the same instance.")));
}
}

private void AddUserManagerInterfaces() {
Services.TryAddScoped<IUserPasswordManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserEmailManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserPhoneNumberManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserLoginManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserClaimManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserRoleManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserTwoFactorManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserLockoutManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
Services.TryAddScoped<IUserTokenManager<TUser>>(sp => sp.GetRequiredService<RuntimeAppsUserManager<TUser>>());
}
public RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddUserMapper<TUserDto>(Func<TUser, TUserDto> toDto, Func<TUserDto, TUser> toUser) where TUserDto : class {
ArgumentNullException.ThrowIfNull(toDto); ArgumentNullException.ThrowIfNull(toUser);
Services.Replace(ServiceDescriptor.Singleton<IUserMapper<TUser, TUserDto>>(new DelegateUserMapper<TUser, TUserDto>(toDto, toUser)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,12 @@ public static IEndpointRouteBuilder MapAccountApi<TUser, TUserDto, TKey>(this IE
return user != null ? mapper.ToDto(user) : null;
});

authorizedRouteGroup.MapPost("password/change", async Task<Results<Ok, ValidationProblem>> ([FromBody] ChangePasswordModel input, IUserManager<TUser> userManager, HttpContext httpContext, IServiceProvider services) => {
authorizedRouteGroup.MapPost("password/change", async Task<Results<Ok, ValidationProblem>> ([FromBody] ChangePasswordModel input, IUserManager<TUser> userManager, IUserPasswordManager<TUser> 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();

Expand All @@ -193,12 +193,12 @@ public static IEndpointRouteBuilder MapAccountApi<TUser, TUserDto, TKey>(this IE
return TypedResults.Ok();
});

authorizedRouteGroup.MapPost("password", async Task<Results<Ok, ValidationProblem>> ([FromBody] string password, IUserManager<TUser> userManager, HttpContext httpContext, IServiceProvider services) => {
authorizedRouteGroup.MapPost("password", async Task<Results<Ok, ValidationProblem>> ([FromBody] string password, IUserManager<TUser> userManager, IUserPasswordManager<TUser> 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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(this IEndpoi

routes.MapPost("refresh", async Task<IResult> (HttpContext context,
IUserManager<TUser> userManager,
IUserLockoutManager<TUser> lockoutManager,
IUserLoginManager<TUser> loginManager,
ISignInManager<TUser> signInManager,
IRefreshTokenService<TKey> refreshTokenService,
IRefreshTokenRequestLimiter requestLimiter,
Expand Down Expand Up @@ -56,8 +58,8 @@ public static IEndpointRouteBuilder MapRefreshTokenApi<TUser, TKey>(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 ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ public static IEndpointRouteBuilder MapUserClaimGetApi<TUser>(this IEndpointRout
where TUser : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapGet("{userId}/claim", async Task<Results<Ok<IEnumerable<ClaimDto>>, ValidationProblem>> ([FromRoute] string userId, IUserManager<TUser> userManager) => {
routeGroup.MapGet("{userId}/claim", async Task<Results<Ok<IEnumerable<ClaimDto>>, ValidationProblem>> ([FromRoute] string userId, IUserManager<TUser> userManager, IUserClaimManager<TUser> 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)));
});

Expand All @@ -27,45 +27,45 @@ public static IEndpointRouteBuilder MapUserClaimManageApi<TUser>(this IEndpointR
where TUser : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapPost("{userId}/claim", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager<TUser> userManager) => {
routeGroup.MapPost("{userId}/claim", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager<TUser> userManager, IUserClaimManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager<TUser> userManager) => {
routeGroup.MapDelete("{userId}/claim", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager<TUser> userManager, IUserClaimManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<ClaimDto> claims, IUserManager<TUser> userManager) => {
routeGroup.MapPost("{userId}/claim/bulk", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<ClaimDto> claims, IUserManager<TUser> userManager, IUserClaimManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<ClaimDto> claims, IUserManager<TUser> userManager) => {
routeGroup.MapDelete("{userId}/claim/bulk", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<ClaimDto> claims, IUserManager<TUser> userManager, IUserClaimManager<TUser> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ public static IEndpointRouteBuilder MapUserRoleGetApi<TUser>(this IEndpointRoute
where TUser : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapGet("{userId}/Role", async Task<Results<Ok<IList<string>>, ValidationProblem>> ([FromRoute] string userId, IUserManager<TUser> userManager) => {
routeGroup.MapGet("{userId}/Role", async Task<Results<Ok<IList<string>>, ValidationProblem>> ([FromRoute] string userId, IUserManager<TUser> userManager, IUserRoleManager<TUser> 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);
});

Expand All @@ -27,48 +27,48 @@ public static IEndpointRouteBuilder MapUserRoleManageApi<TUser>(this IEndpointRo
where TUser : class {
var routeGroup = endpoints.MapGroup("");

routeGroup.MapPost("{userId}/Role", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<string> roles, IUserManager<TUser> userManager) => {
routeGroup.MapPost("{userId}/Role", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<string> roles, IUserManager<TUser> userManager, IUserRoleManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<string> roles, IUserManager<TUser> userManager) => {
routeGroup.MapDelete("{userId}/Role", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromBody] IEnumerable<string> roles, IUserManager<TUser> userManager, IUserRoleManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager<TUser> userManager) => {
routeGroup.MapPost("{userId}/Role/{roleName}", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager<TUser> userManager, IUserRoleManager<TUser> 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<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager<TUser> userManager) => {
routeGroup.MapDelete("{userId}/Role/{roleName}", async Task<Results<Ok, ValidationProblem>> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager<TUser> userManager, IUserRoleManager<TUser> 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();

Expand Down
Loading
Loading