0

Using Identity 2.0, I have modified to use integer as primary key following http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

It works great except when from the controller, I call:

User.IsUserInRole("admin");

It always returns false. I have checked the underlying table and data is fine.

However, if I do:

var t = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
bool ok = t.IsInRole(User.Identity.GetUserId<int>(), "admin");

then it works fine. It seems that the problem is only in Controller.User

Also, attributes do not work, for example [Authorize(Roles = "admin")]

Somebody have had the same problem?

UPDATE:

It is nothing related with the controller, Thread.CurrentPrincipal has the same problem:

Thread.CurrentPrincipal.IsInRole("admin");

UPDATE 2:

It seems that the problem is in the AspNetUserRoles table. Identity has added a new column, a foreign key to my extended user table. It seems redundant to me because there is UserId column. The problem is all values of this column are NULL. I think if I am able to understand how to redirect to UserId, everything will work fine.

Dabiel Kabuto
  • 2,762
  • 4
  • 29
  • 45
  • [Authorize(Roles = "admin")] and User.IsInRole checking the cookie which created during the login. There should be something wrong the way you set authentication cookie which hasn't included role information of the user. – DSR Nov 05 '14 at 13:50
  • DSR, however the following code works fine: var t = HttpContext.GetOwinContext().GetUserManager(); bool ok = t.IsInRole(User.Identity.GetUserId(), "admin"); – Dabiel Kabuto Nov 05 '14 at 15:54
  • Yes, that's right, because you accessing the database directly using that code. [Authorize(Roles = "admin")] and User.IsInRole does not access database instead getting information from authentication cookie. Post your owin start up code where you set up your authentication cookies. Follow these video tutorials http://stackoverflow.com/questions/25857806/extending-identityuserrole-in-identity-2-0/25857923#25857923 – DSR Nov 05 '14 at 16:15

2 Answers2

0

Try to add Role claim when user signs in

Andrei
  • 42,814
  • 35
  • 154
  • 218
0

I solved it: The problem was I created a class derived from IdentityUser, additionally I enabled Table per Type (TPT) by mistake, adding the table name. Identity 2.0 added a third column in AspNetUserRoles pointing to this new type, and since it was null, there were not roles. Now, I use Table Per Hierarchy (TPH) and everything works fine.

Dabiel Kabuto
  • 2,762
  • 4
  • 29
  • 45