Reputation: 78
I set up AutoFac to work with ASP.NET Identity in MVC 5. Everything seemed to work fine on surface, i.e. users could create accounts and log in. But then I discovered that the users do not get logged out when Security Stamp is changed. Either by brute force in AspNetUsers table or by users changing password and expecting to be logged out in other browser.
This is how I set up AutoFac by following this unofficial article.
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);
}
This is how I set up the cookie authentication middleware. It's default except for validate interval shorter timespan.
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))
}
});
}
If I set breakpoint in GenerateUserIdentityAsync then it gets called only when user logs in the first time.
Upvotes: 2
Views: 1304
Reputation: 35106
Security stamp validator needs ApplicationUserManager
and it tries to resolve the instance from OWIN context (because it does not know any better). So you still need to register ApplicationUsreManager
with OWIN:
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
Upvotes: 5