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: