asp.netsimplemembershipasp.net-mvc-5asp.net-identityrole-manager

RoleManager and SimpleMembershipProvider cannot be used with AuthorizeAttribute


I have an Asp.Net MVC 5 application. I want to use user roles to authorize only some people to use a specific action. I've changed my Web.config file like this:

<roleManager enabled="true"/>
<membership defaultProvider="SimpleMembershipProvider">
  <providers>
    <clear/>
    <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
  </providers>
</membership>

This is how I add users to roles:

if (!await Roles.RoleExists(role))
    await Roles.CreateRole(new Role(role));
await Roles.AddUserToRole(role, user.Id);

Currently I am able to access the roles for a user through code using something like this:

    public static async Task<IEnumerable<string>> GetUserRoles(string username)
    {
        if (string.IsNullOrEmpty(username))
            return new string[0];
        string userId = await Logins.GetUserId(IdentityConfig.LocalLoginProvider, username);
        var roles = await Roles.GetRolesForUser(userId);
        return roles;
    }

However, when I try to use the Authorize attribute to access the roles, the page will get stuck and nothing loads.

[Authorize(Roles = "Admin")]
public ActionResult Index()
{
    return View(db.Restaurants.ToList());
}

What am I doing wrong here?

Update:

After a while the webpage will show this error:

Asp.Net error page


Solution

  • You cannot really mix the old membership/roles with the new identity system. You need to pick one or the other. The authorize attribute should work fine assuming you added the user to the admin role via the new identity apis.

    At the bottom, this article demonstrates roles Mvc5 tutorial