我正在使用 IdentityServer3 进行身份验证。所有用户都存储在 Sql DB 中,所以我也在使用Microsoft.AspNet.Identity
实际身份验证的框架,出于同样的目的,我创建了自己的框架ApplicationUserManager
class.
AspNet 身份将 IoC 功能集成到 OWIN 中间件中。并且它注册了ApplicationUserManager
like:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
它接受函数委托,返回一个新的实例ApplicationUserManager
public static ApplicationUserManager
Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
然而,IdentityServer 使用自己的 DI 框架并且(i think)我们不能使用静态Create()
注册方法ApplicationUserManager
还可以使用 IdentityServerCreate()
方法需要IdentityFactoryOptions
and a IOwinContext
作为参数。
我跟着这个SO post我改变了实施ApplicationUserManager
使用构造函数注入
public class ApplicationUserManager : UserManager<ApplicationUser, string>
{
public ApplicationUserManager(ApplicationUserStore store, IdentityFactoryOptions<ApplicationUserManager> options)
: base(store)
{
// Configure validation logic for usernames
UserValidator = new UserValidator<ApplicationUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
UserLockoutEnabledByDefault = true;
DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
MaxFailedAccessAttemptsBeforeLockout = 5;
EmailService = new EmailService();
SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
}
}
然后将所有服务注册到IdentityServer自己的DI框架中,如下所示
factory.UserService = new Registration<IUserService, UserService>();
factory.Register(new Registration<ApplicationUserManager>());
factory.Register(new Registration<ApplicationUserStore>());
factory.Register(new Registration<IdentityFactoryOptions<ApplicationUserManager>>(resolver => new IdentityFactoryOptions<ApplicationUserManager>
{
DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ASP.NET Identity")
}));
factory.Register(new Registration<ApplicationDbContext>(resolver => new ApplicationDbContext(ApplicationConfig.ConnectionString)));
问题
- 这是正确的注册方式吗
ApplicationUserManager
和
IdentityServer的DI框架?
- 我正在创造
DataProtectionProvider
在注册期间和UserTokenProvider
在构造函数内部。 IdentityServer 如何使用这两个提供程序?
- 请注意,我没有注册
IOwinContext
从那时起任何地方
ApplicationUserManager的构造函数不再需要它,将
这会导致 OWIN 管道出现任何问题吗?
- 什么是理想的注册模式
ApplicationUserManager
?