Closed irfan-yusanif closed 4 years ago
I'm implementing dependency injection to an existing asp.net MVC website that uses identity for login. User.Identity.IsAuthenticated is always false
I installed NuGet package: Install-Package Unity.Mvc
Install-Package Unity.Mvc
Added the following code in Unity.Config
container.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager()); container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager()); container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager()); var accountInjectionConstructor = new InjectionConstructor(new ApplicationDbContext()); container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor); container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
AccountController.cs
private readonly UserManager<ApplicationUser> UserManager; private readonly IAuthenticationManager AuthenticationManager; public AccountController(IUserStore<ApplicationUser> userStore, IAuthenticationManager authManager) { UserManager = new UserManager<ApplicationUser>(userStore); AuthenticationManager = authManager; }
method to sign in
private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); //identity.IsAuthenticated is true AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); //User.Identity.IsAuthenticated is false }
Issue: Please check above commented lines, identity.IsAuthenticated is true (that's fine) but User.Identity.IsAuthenticated is still false.
How to update this identity in HttpContext.User.Identity?
ConfigureAuth() in startup.Auth.cs was not being called. Calling this function fixed the issue
ConfigureAuth()
startup.Auth.cs
I'm implementing dependency injection to an existing asp.net MVC website that uses identity for login. User.Identity.IsAuthenticated is always false
I installed NuGet package:
Install-Package Unity.Mvc
Added the following code in Unity.Config
AccountController.cs
method to sign in
Issue: Please check above commented lines, identity.IsAuthenticated is true (that's fine) but User.Identity.IsAuthenticated is still false.
How to update this identity in HttpContext.User.Identity?