using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using zero.Identity;
namespace zero.Identity;
public static class ServiceCollectionExtensions
{
///
/// Adds the default identity system configuration for the specified User and Role types
///
// public static IdentityBuilder AddZeroIdentity(
// this IServiceCollection services)
// where TUser : ZeroIdentityUser, new()
// where TRole : ZeroIdentityRole, new()
// where TStore : class, IZeroIdentityStoreDbProvider
// => services.AddIdentity(setupAction: null!);
///
/// Adds and configures the identity system for the specified User and Role types
///
public static IdentityBuilder AddZeroIdentity(
this IServiceCollection services,
Action setupAction
)
where TUser : ZeroIdentityUser, new()
where TRole : ZeroIdentityRole, new()
where TStore : class, IZeroIdentityStoreDbProvider
{
// Services used by identity
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddCookie(IdentityConstants.ApplicationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
};
})
.AddCookie(IdentityConstants.ExternalScheme, o =>
{
o.Cookie.Name = IdentityConstants.ExternalScheme;
o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
})
.AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
o.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = SecurityStampValidator.ValidateAsync
};
})
.AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});
// Hosting doesn't add IHttpContextAccessor by default
services.AddHttpContextAccessor();
// Data stores
services.AddScoped();
services.TryAddScoped, ZeroUserStore>();
services.TryAddScoped, ZeroRoleStore>();
// Identity services
services.TryAddScoped, UserValidator>();
services.TryAddScoped, PasswordValidator>();
services.TryAddScoped, PasswordHasher>();
services.TryAddScoped();
services.TryAddScoped, RoleValidator>();
services.TryAddScoped();
services.TryAddScoped>();
services.TryAddScoped>();
services.TryAddScoped, UserClaimsPrincipalFactory>();
services.TryAddScoped, DefaultUserConfirmation>();
services.TryAddScoped>();
services.TryAddScoped>();
services.TryAddScoped>();
if (setupAction != null)
{
services.Configure(setupAction);
}
return new IdentityBuilder(typeof(TUser), typeof(TRole), services);
}
}