我设置AutoFac以在MVC 5中使用ASP.NET身份。一切似乎在表面上工作正常,即用户可以创建帐户并登录。但后来我发现安全戳时用户不会被注销改变了。通过AspNetUsers表中的暴力破解或用户更改密码并期望在其他浏览器中注销。
这是我按照this unofficial article设置AutoFac的方式。
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
builder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
ConfigureAuth(app);
}
这就是我设置cookie身份验证中间件的方法。除了验证间隔更短的时间间隔外,它是默认值。
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromSeconds(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
}
如果我在 GenerateUserIdentityAsync 中设置断点,则仅在用户第一次登录时才会调用它。
答案 0 :(得分:4)
安全标记验证程序需要ApplicationUserManager
并尝试从OWIN上下文中解析该实例(因为它不知道更好)。因此,您仍然需要向OWIN注册ApplicationUsreManager
:
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());