C# 向Unity注册IAAuthenticationManager
我使用Unity进行依赖注入,并使用Identiy Provider管理用户登录、注册、电子邮件确认等 当我尝试注册用户时,我遇到以下问题: 当前类型为Microsoft.Owin.Security.IAAuthenticationManager 无法构造接口和。你缺一种吗 映射 我不知道如何在Unity容器中注册此接口(IAAuthenticationManager) 我尝试使用此代码注册接口,但如果我使用此代码,则会出现其他问题: 没有注册IUserTokenProvider IdentityConfig.csC# 向Unity注册IAAuthenticationManager,c#,unity-container,asp.net-identity,C#,Unity Container,Asp.net Identity,我使用Unity进行依赖注入,并使用Identiy Provider管理用户登录、注册、电子邮件确认等 当我尝试注册用户时,我遇到以下问题: 当前类型为Microsoft.Owin.Security.IAAuthenticationManager 无法构造接口和。你缺一种吗 映射 我不知道如何在Unity容器中注册此接口(IAAuthenticationManager) 我尝试使用此代码注册接口,但如果我使用此代码,则会出现其他问题: 没有注册IUserTokenProvider Identit
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your sms service here to send a text message.
return Task.FromResult(0);
}
}
// This is useful if you do not want to tear down the database each time you run the application.
// public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
// This example shows you how to create a new database if the Model changes
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin@example.com";
const string password = "Admin@123456";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
:
base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
公共类应用程序管理员:用户管理员
{
公共应用程序服务器管理器(IUserStore存储)
:基地(商店)
{
}
公共静态应用程序SerManager创建(IdentityFactoryOptions选项,
IOwinContext(上下文)
{
var manager=newapplicationUserManager(newuserstore(context.Get());
//为用户名配置验证逻辑
manager.UserValidator=新的UserValidator(管理器)
{
AllowOnlyAlphanumericUserNames=false,
RequireUniqueEmail=true
};
//配置密码的验证逻辑
manager.PasswordValidator=新密码验证器
{
所需长度=6,
RequiredOnletterDigit=真,
RequireDigit=true,
RequireLowercase=true,
RequireUppercase=true,
};
//配置用户锁定默认值
manager.UserLockoutEnabledByDefault=true;
manager.DefaultAccountLockoutTimeSpan=TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout=5;
//注册双因素身份验证提供商。此应用程序使用电话和电子邮件作为接收验证用户代码的步骤
//您可以编写自己的提供程序并在此处插入。
manager.RegisterWofactorProvider(“PhoneCode”,新的PhoneNumberTokenProvider
{
MessageFormat=“您的安全代码为:{0}”
});
manager.RegisterWofactorProvider(“EmailCode”,新的EmailTokenProvider
{
Subject=“SecurityCode”,
BodyFormat=“您的安全代码为{0}”
});
manager.EmailService=新的EmailService();
manager.SmsService=新的SmsService();
var dataProtectionProvider=options.dataProtectionProvider;
if(dataProtectionProvider!=null)
{
manager.UserTokenProvider=
新的DataProtectorTokenProvider(dataProtectionProvider.Create(“ASP.NET标识”);
}
退货经理;
}
}
//配置应用程序中使用的角色管理器。角色管理器在ASP.NET标识核心程序集中定义
公共类应用程序RoleManager:RoleManager
{
公共应用程序角色管理器(IRoleStore角色存储库)
:底座(roleStore)
{
}
公共静态应用程序角色管理器创建(IdentityFactoryOptions选项,IOwinContext上下文)
{
返回新的ApplicationRoleManager(新的RoleStore(context.Get());
}
}
公共类电子邮件服务:IIdentityMessageService
{
公共任务SendAsync(IdentityMessage消息)
{
//在此处插入电子邮件服务以发送电子邮件。
返回Task.FromResult(0);
}
}
公共类SMS服务:IIdentityMessageService
{
公共任务SendAsync(IdentityMessage消息)
{
//在此处插入您的短信服务以发送短信。
返回Task.FromResult(0);
}
}
//如果您不希望每次运行应用程序时都拆下数据库,这将非常有用。
//公共类ApplicationBinInitializer:DropCreateDatabaseAlways
//此示例演示了如何在模型更改时创建新数据库
公共类ApplicationBinInitializer:DropCreateDatabaseIfModelChanges
{
受保护的重写无效种子(ApplicationDbContext上下文)
{
InitializeIdentityFore(上下文);
种子(上下文);
}
//创建用户=Admin@Admin.com带密码=Admin@123456在管理员角色中
公共静态void initializedEntityForef(ApplicationDbContext数据库)
{
var userManager=HttpContext.Current.GetOwinContext().GetUserManager();
var rolemager=HttpContext.Current.GetOwinContext().Get();
常量字符串名称=”admin@example.com";
常量字符串密码=”Admin@123456";
常量字符串roleName=“Admin”;
//如果角色Admin不存在,则创建该角色
var role=rolemager.FindByName(roleName);
如果(角色==null)
{
角色=新的识别码(roleName);
var roleresult=rolemanger.Create(角色);
}
var user=userManager.FindByName(名称);
if(user==null)
{
user=newapplicationuser{UserName=name,Email=name};
var result=userManager.Create(用户,密码);
结果=userManager.SetLockoutEnabled(user.Id,false);
}
//将用户管理员添加到角色管理员(如果尚未添加)
var rolesForUser=userManager.GetRoles(user.Id);
如果(!rolesForUser.Contains(role.Name))
{
var result=userManager.AddToRole(user.Id,role.Name);
}
}
}
公共类应用程序SignInManager:SignInManager
{
公共应用程序SigninManager(ApplicationUserManager用户管理器,IAAuthenticationManager authentica
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your sms service here to send a text message.
return Task.FromResult(0);
}
}
// This is useful if you do not want to tear down the database each time you run the application.
// public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
// This example shows you how to create a new database if the Model changes
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin@example.com";
const string password = "Admin@123456";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
:
base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
container.RegisterType<DbContext, ApplicationDbContext>(
new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(
new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
new HierarchicalLifetimeManager());
container.RegisterType<AccountController>(
new InjectionConstructor());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(
o => System.Web.HttpContext.Current.GetOwinContext().Authentication
)
);
container.RegisterType<ManageController>(new InjectionConstructor());
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<MyDbContext>(new PerRequestLifetimeManager(), new InjectionConstructor());
// Identity
container.RegisterType<UserManager<User>>(new HierarchicalLifetimeManager());
container.RegisterType<SignInManager<User, string>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<User>, UserStore<User>>(new PerRequestLifetimeManager(), new InjectionFactory(x => new UserStore<User>(GetConfiguredContainer().Resolve<MyDbContext>())));
container.RegisterType<IAuthenticationManager>(new InjectionFactory(x => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterFactory<IAuthenticationManager>(o => System.Web.HttpContext.Current.GetOwinContext().Authentication);