User.IsInRole doesn't work

40,210

Solution 1

I had a smilar issue. In my case the problem solved when i log off and log in again.

Solution 2

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

Solution 3

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.

Solution 4

Have you tried adding

[InitializeSimpleMembership]

in the controller where you're doing the check?

Solution 5

I had a similar problem with IsUserInRole returning false. By placing a watch on it, I was able to overcome the problem by using the overload described below. Try it, put a break point where you're getting false, and see what happens.

@if (Roles.IsUserInRole(Model.UserName, "Administrator"))

I'm pretty sure you could also use User.Identity.Name as the first parameter.

Share:
40,210
Bartosz
Author by

Bartosz

Updated on January 03, 2021

Comments

  • Bartosz
    Bartosz over 3 years

    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 which expires 100 days from login date. And everything works fine, apart of main menu of the application.

    Some parts of the menu are available for admin users only. I use:

    @if (User.IsInRole("Administrator")) { @Html.Partial("_MainMenuPartial") }
    

    to lock them from being rendered for regular user. This approach works fine just after logging into the system. When I return after a while and persistent cookie is used to authenticate me, I do get logged in, but

    @User.IsInRole("Administrator")
    

    returns "False" so I can't see admin menu items. At the same time

    @User.Identity.Name
    

    returns proper login name and

    @User.Identity.IsAuthenticated
    

    returns "True", what proves that persistent cookie works fine. Why can't I access user roles even though user is authenticated by the system then?