注册IAuthenticationManager使用Unity [英] Register IAuthenticationManager with Unity

查看:805
本文介绍了注册IAuthenticationManager使用Unity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Unity的依赖注入,并使用同一性提供商来管理用户登录,注册,确认电子邮件等。



当我尝试注册一个用户,我有这样的问题:




当前类型,Microsoft.Owin.Security.IAuthenticationManager是
接口,不能建。是否缺少类型
映射?




我不知道如何在我的团结容器注册此接口(IAuthenticationManager)



我尝试注册与此代码的接口,但如果我把它,我还有其他问题:



<块引用>

没有IUserTokenProvider注册




  container.RegisterType< HttpContextBase> (
新InjectionFactory(_ =>新建HttpContextWrapper(HttpContext.Current)));
container.RegisterType&所述; IOwinContext>(新InjectionFactory(C => c.Resolve&下; HttpContextBase方式>()GetOwinContext()));
container.RegisterType< IAuthenticationManager>(
新InjectionFactory(C => c.Resolve< IOwinContext>()认证)。);



我把应用程序的一些代码(如果我不使用统一,所有的工作罚款):



的AccountController

 私人IAuthenticationManager的AuthenticationManager 
{
得到
{
返回HttpContext.GetOwinContext()认证;
}
}



IdentityConfig.cs

 公共类ApplicationUserManager:&的UserManager LT; ApplicationUser> 
{
公共ApplicationUserManager(IUserStore< ApplicationUser>存储)
:基(存储)
{

}

公静态ApplicationUserManager创建(IdentityFactoryOptions< ApplicationUserManager>选项,
IOwinContext上下文)
{
变种经理=新ApplicationUserManager(新UserStore< ApplicationUser>(context.Get< ApplicationDbContext>())); ApplicationUser>(经理)
{
AllowOnlyAlphanumericUserNames =假,
RequireUniqueEmail = TRUE $ B $的用户名
manager.UserValidator =新UserValidator和LT
//配置验证逻辑b};
//配置口令
manager.PasswordValidator =新PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit =验证逻辑真,
RequireDigit = TRUE,
RequireLowercase = TRUE,
RequireUppercase = TRUE,
};
//配置用户锁定的默认值
manager.UserLockoutEnabledByDefault = TRUE;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
//注册双因素身份验证提供者。此应用程序使用手机和电子邮件作为接收码验证用户
//你可以编写自己的供应商,在这里插上的步骤。
manager.RegisterTwoFactorProvider(手机密码,新PhoneNumberTokenProvider< ApplicationUser>
{
MessageFormat =您的安全代码是:{0}
});
manager.RegisterTwoFactorProvider(EmailCode,新EmailTokenProvider< ApplicationUser>
{
主题=SecurityCode,
BodyFormat =您的安全码是{0}
});
manager.EmailService =新EmailService();
manager.SmsService =新SmsService();
VAR dataProtectionProvider = options.DataProtectionProvider;
如果(dataProtectionProvider!= NULL)
{
manager.UserTokenProvider =
新DataProtectorTokenProvider< ApplicationUser>(dataProtectionProvider.Create(ASP.NET身份));
}
返回经理;
}
}

//配置RoleManager应用程序中使用。 RoleManager在ASP.NET识别核心装配
公共类ApplicationRoleManager定义:RoleManager< IdentityRole>
{
公共ApplicationRoleManager(IRoleStore< IdentityRole,串> Rolestore的)
:基地(Rolestore的)
{
}

公共静态ApplicationRoleManager创建(IdentityFactoryOptions< ApplicationRoleManager>选项,IOwinContext上下文)
{
返回新ApplicationRoleManager(新Rolestore的< IdentityRole>(context.Get< ApplicationDbContext>()));
}
}

公共类EmailService:IIdentityMessageService
{
公共任务SendAsync(IdentityMessage消息)
{
//插上您的电子邮件服务在这里发送电子邮件。
返回Task.FromResult(0);
}
}

公共类SmsService:IIdentityMessageService
{
公共任务SendAsync(IdentityMessage消息)
{
//插入您的短信服务在这里发送短信。
返回Task.FromResult(0);
}
}

//如果你不希望每次运行应用程序时推倒数据库,这非常有用。
//公共类ApplicationDbInitializer:DropCreateDatabaseAlways< ApplicationDbContext>
//这个例子向您展示了如何在模型的变化
公共类ApplicationDbInitializer创建一个新的数据库:DropCreateDatabaseIfModelChanges< ApplicationDbContext>
{
保护覆盖无效种子(ApplicationDbContext上下文)
{
InitializeIdentityForEF(背景);
base.Seed(上下文);
}

//使用密码创建User=Admin@Admin.com = Admin角色
公共静态无效InitializeIdentityForEF(ApplicationDbContext DB)
{@管理员123456
变种的UserManager = HttpContext.Current.GetOwinContext()GetUserManager< ApplicationUserManager>();
VAR roleManager = HttpContext.Current.GetOwinContext()获取< ApplicationRoleManager>();
常量字符串名称=admin@example.com;
常量字符串密码=管理@ 123456;
常量字符串角色名=管理;

//创建角色admin,如果它不存在,
VAR作用= roleManager.FindByName(角色名);
如果(角色== NULL)
{
=角色新IdentityRole(角色名);
VAR roleresult = roleManager.Create(作用);
}

VAR用户= userManager.FindByName(名);
如果(用户== NULL)
{
用户=新ApplicationUser {用户名=名称,电子邮件=名};
VAR的结果= userManager.Create(用户名,密码);
结果= userManager.SetLockoutEnabled(user.Id,FALSE);
}

//添加用户管理员角色admin,如果尚未添加
VAR rolesForUser = userManager.GetRoles(user.Id);
如果
{
VAR的结果= userManager.AddToRole(user.Id,role.Name)(rolesForUser.Contains(role.Name)!);
}
}
}

公共类ApplicationSignInManager:SignInManager< ApplicationUser,串>
{
公共ApplicationSignInManager(ApplicationUserManager的UserManager,IAuthenticationManager AuthenticationManager会)

基地(的UserManager,AuthenticationManager会)
{



}

公众覆盖任务< ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser用户)
{
返回user.GenerateUserIdentityAsync((ApplicationUserManager)的UserManager);
}

公共静态ApplicationSignInManager创建(IdentityFactoryOptions< ApplicationSignInManager>选项,IOwinContext上下文)
{
返回新ApplicationSignInManager(context.GetUserManager< ApplicationUserManager>(),上下文.Authentication);
}
}



谢谢!


解决方案

下面是我做过什么,使团结发挥好与ASP.NET 2.0身份:



我增加了以下到 UnityConfig 类的<​​code> RegisterTypes 方法:

  container.RegisterType<的DbContext,ApplicationDbContext>(
新HierarchicalLifetimeManager());
container.RegisterType&所述;的UserManager&下; ApplicationUser>>(
新HierarchicalLifetimeManager());
container.RegisterType&所述; IUserStore&下; ApplicationUser>中UserStore&所述; ApplicationUser>>(
新HierarchicalLifetimeManager());

container.RegisterType<&的AccountController GT;(
新InjectionConstructor());


I'm using Unity for Dependencies Injection and using Identiy Provider to manage the user login, register, email confirmation, etc.

When I try to register a user, I have this problem:

The current type, Microsoft.Owin.Security.IAuthenticationManager, is an interface and cannot be constructed. Are you missing a type mapping?

I have no idea how to register this Interface (IAuthenticationManager) in my Unity container.

I tried registering the interface with this code, but if I put it, I have other problem:

No IUserTokenProvider is registered.

 container.RegisterType<HttpContextBase>(
            new InjectionFactory(_ => new HttpContextWrapper(HttpContext.Current)));
        container.RegisterType<IOwinContext>(new InjectionFactory(c => c.Resolve<HttpContextBase>().GetOwinContext()));
        container.RegisterType<IAuthenticationManager>(
            new InjectionFactory(c => c.Resolve<IOwinContext>().Authentication));

I put some code of the app (If I don't use Unity, all work fine):

AccountController

private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

IdentityConfig.cs

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);
        }
    }

Thanks!!

解决方案

Here is what I did to make Unity play nice with ASP.NET Identity 2.0:

I added the following to the RegisterTypes method in the UnityConfig class:

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());

这篇关于注册IAuthenticationManager使用Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆