Autofac with ASP.NET Identity in MVC 5 does not validate Security Stamp in OWIN pipeline

做~自己de王妃 提交于 2019-12-11 03:35:00

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/40185064/autofac-with-asp-net-identity-in-mvc-5-does-not-validate-security-stamp-in-owin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!