User.IsInRole doesn't work

后端 未结 16 1353
北恋
北恋 2020-12-05 18:29

I have ASP.NET MVC 4 application. I use Simple Membership Provider allowing to tick remember me checkbox under login form. If ticked, persitent cookie .ASPXAUTH is created w

相关标签:
16条回答
  • 2020-12-05 18:38

    Add Page in front of User. This works: Page.User.IsInRole("Administrator")

    0 讨论(0)
  • 2020-12-05 18:42

    If you are using latest Identity framework please see if you are using following

    services.AddIdentity<IdentityUser,IdentityRole>()
            .AddEntityFrameworkStores<WebUserContext>()
            .AddDefaultTokenProviders();
    

    If you are using AddDefaultIdentity Roles don't get populated.

    services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<WebUserContext>()
            .AddDefaultTokenProviders();
    
    0 讨论(0)
  • 2020-12-05 18:46

    The "EmailConfirmed" of this account probably still false, try to change it to true

    Database Screenshot

    0 讨论(0)
  • 2020-12-05 18:47

    I've been struggling with the MVC5 role manager for some time now. I've verified that User.IsInRole can return different results at the same time, and apparently this is because the User object is cached and needs to be invalidated. One way to do this is to log out and log back in again as one of the answers here specified. Just throw this in the controller that adds the new role:

            UserManager.AddToRole(User.Identity.GetUserId(), "Administrator");
    
            var updatedUser = await UserManager.FindByNameAsync(User.Identity.Name);
            var newIdentity = await updatedUser.GenerateUserIdentityAsync(UserManager);
            AuthenticationManager.SignOut();
            AuthenticationManager.SignIn(newIdentity);
    

    However, if the user has your application open in other windows this won't update all of them.

    0 讨论(0)
  • 2020-12-05 18:48

    Old question, but there's some missing information here. I ran into the same issue, and there's one thing to keep in mind. If you test the user identity (like User.IsInRole("admin")) just after authenticate (without send the response to client), Identity framework has not populated this session info yet (or at least, I could not found the way to do that). This info you're requesting for, is populated at some point after your controller return. If you want (I.E.) to redirect to different views after login, depending on the user role, you'll have to use a custom authorization filter.

    0 讨论(0)
  • 2020-12-05 18:50

    Problem using roles with MVC5

    I found a solution. In my web.config:

    <modules>
        <remove name="FormsAuthenticationModule" />
        <remove name="RoleManager" />
    </modules>
    

    I added remove name="RoleManager" line, and the new AspNet.Identity code took over allowing me to use User.IsInRole(..)

    http://forums.asp.net/t/1952572.aspx?Problem+using+roles+with+MVC5

    0 讨论(0)
提交回复
热议问题