I have an ASP.NET MVC 5 application. I’m using the standard ASP.NET Identity provider for user and role management. It is important that I’m using the IdentityUser from an own repository project, but this seems ok. I can register, login, edit users, and manage their roles.
I add user to Role with these lines:
UserManager.AddToRole(userdetail.Id, r); db.Entry(userdetail).State = EntityState.Modified; db.SaveChanges();
This seems working in DB level.
But, I can’t use Role based authentications, actually the simples
HttpContext.User.IsInRole("Administrator")
doesn’t working too.
[Authorize(Roles="Administrator")]
doesn’t working too.
I can check only with this method, whether user is an administrator:
UserManager.IsInRole(userID, "Administrator").
Why?
In every tutorial what I found, everything works fine. The different project repository could be the reason? Or ASP.NET Identity is broken so much?
Please advice,
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In that case you need to logout and login the user again.
Because the roles data is also stored in cookies,
So you must issue the cookie again to work it.
Method 2
There seems to be an issue. [The issue by design]
- The role names are case sensitive in AuthorizeAttribute and User.IsInRole
- The role names are case insensitive in UserManager.IsInRole
Moreover, check for the correct role name is used for the verification.
[The above is based on the test performed with below code. Role Name=”Admin”, User is added to Role “Admin”.]
[Authorize(Roles="Admin")] /*True as "Admin" has A capital as entered in Role name*/
public ActionResult Secured()
{
if (User.IsInRole("admin")) /*This is False*/
{
Console.WriteLine("In");
}
if(UserManager.IsInRole(User.Identity.GetUserId(), "admin")) /*This is True!!*/
{
Console.WriteLine("In");
}
return View();
}
If we change the attribute to [Authorize(Roles="admin")], it redirects to Login page.
Method 3
Do you have this entry in your web.config?
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="ApplicationServices" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" applicationName="/" />
</providers>
</roleManager>
Also, if I remember correctly, there is a different namespace for the role provider assembly in different versions of .NET.
Method 4
I was using IsInRoleAsync in Asp.Net core and in my case the problem was that I have ignored the role’s normalized name when I created it. Therefore, after updating the normalized name for the role everything worked properly.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0