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.Raven;
public static class ServiceCollectionExtensions
{
///
/// Adds the default identity system configuration for the specified User and Role types, using RavenDB as the data store.
///
public static IdentityBuilder AddRavenDbIdentity(
this IServiceCollection services)
where TUser : ZeroIdentityUser, new()
where TRole : ZeroIdentityRole, new()
=> services.AddIdentity(setupAction: null!);
///
/// Adds and configures the identity system for the specified User and Role types, using RavenDB as the data store.
///
public static IdentityBuilder AddRavenDbIdentity(
this IServiceCollection services,
Action setupAction
)
where TUser : ZeroIdentityUser, new()
where TRole : ZeroIdentityRole, new()
{
// 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.TryAddScoped, RavenUserStore>();
services.TryAddScoped, RavenRoleStore>();
// 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);
}
}