Question

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

Was it helpful?

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

OTHER TIPS

I had the same problem, it has nothing to do with your connection string. Add the following to your web.config:

Here's the answer: http://blog.luppes.com/2013/12/08/mvc5-authentication-roles-failure/

As of ASP.NET 4.5.1/VS2013, MVC as of MVC5 is no longer a separate product, but is now completely integrated into ASP.NET. This is part of Microsoft's new One ASP.NET strategy.

In addition to this, Microsoft has developed a new kind of identity management system called the ASP.NET Identity, which does not use the legacy membership system.

Basically, if you want to use the old membership system, you need to use MVC4 or earlier. If you want to use ASP.NET Identity, then MVC5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top