User.IsInRole() does not work right after role assignment, but does after re-login

user2673195

In a ASP.NET MVC 5 application I'm using Unity container to create OWIN/Identity objects and resolve all the dependencies.

The problem is when I register as a new user and assign him a role like this

userManager.AddToRole(user.Id, "NewUser");
...
await userManager.UpdateAsync(user);

it actually creates a record in AspNetUserRoles table, but right after that if I check his role with User.IsInRole("NewUser") I get false, unless I log out and then log in again, then it is true.

I guess the problem could be with Identity objects (UserManager, RoleManager, etc.) lifetime management in Unity context.

UnityConfig.cs

public static void RegisterTypes(IUnityContainer container)
{
    // DbContext
    container.RegisterType<DbContext, AppEntitiesDbContext>();
    container.RegisterType<AppIdentityDbContext>();

    // Identity
    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                new InjectionConstructor(typeof(AppIdentityDbContext)));

    container.RegisterType<IAuthenticationManager>(
                new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

    container.RegisterType<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>(
                new InjectionConstructor(typeof(AppIdentityDbContext)));

     container.RegisterType<ApplicationUserManager>();
     container.RegisterType<ApplicationSignInManager>();
     container.RegisterType<ApplicationRoleManager>();
}

IdentityConfig.cs (I use <add key="owin:AppStartup" value="MyApp.IdentityConfig" /> in Web.config)

public class IdentityConfig
{
    public void Configuration(IAppBuilder app)
    {
        var container = UnityConfig.GetConfiguredContainer();

        app.CreatePerOwinContext(() => container.Resolve<AppIdentityDbContext>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationUserManager>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationSignInManager>());
        app.CreatePerOwinContext(() => container.Resolve<ApplicationRoleManager>());

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
        });
    }
}
Shoe

That's because using anything from the User object (IPrincipal) is looking at the identity token of the user for the current HTTP request, not the persisted values of the user.

When you log in that token gets created from the roles and other claims. If you change the user's roles in the database the token needs to be recreated and set as the user's new identity.

When you change a part of the user's identity. Just invalidate the old token and re-issue an new one by signing them out/back in.

private async Task SignInAsync(User user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ArchLinux | Login password does not work after creating new user account

jss and css does not work right after "/"

Ubuntu Login Screen does not work After Suspend

How does the role assignment work in Postgres Operator?

Django authenticate user does not work after logging in

User.IsInRole("Admin") and everything related to it does not work

Why does my JavaScript function work but displays "undefined" right after?

Google login does not work on Android after publication in Google Play (Flutter )

laravel 5 redirect user after login based on user's role

Drawing does not work after resizing user control with Dock is not None

JsonConvert.DeserializeObjects does not work after Linking SDK and User Assemblies

Merit does cease to work after create a second User with Devise

Why does state reset to nil after assignment

jquery - css does not work after .after()

JavaScript does not work after outsourcing

Fstab after reboot does not work

Password does not work after lock

Subscription after switchMap does not work

User redirect after login, depending on its role in WooCommerce

Redirect specific user role to specific location after Wordpress login

How to redirect a user with specific "ROLE" to a specific page after login in Wordpress

How to redirect user after login to a desired page according to their role?

User authorization via login does not work

User name is not updated after re-login with different user

Does assignment with a comma work?

How does this assignment work?

dwm does not show any windows after login

FBSDKGraphRequest does not redirect to app after login

14.04 unity does not start after login screen