I just got it to work with my setup that is also using Identity Framework.
I added a user to a role by using the following code:
this.RoleManager.CreateAsync(new Role() {Name = "Customers"});
this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");
Then any time after that, when I ran User.IsInRole("Customers");
it returned false, that was until I relogged them back in.
You need to re-log in the user after having added the user to the role. The role information is stored in the cookies.
I ran the following to log the user again:
var user = await this.UserManager.FindByNameAsync("bob");
var identity = await this.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
this.AuthManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
From this point, User.IsInRole("Customers")
worked for me and returned true
.
This won't work though unless you can verify within your application that it is aware of the role that you want to add them to. You can verify the existence of the role "Customers" by using your RoleManager in the following way:
var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);
[Authorize]
to the controller, do the actions load? – Teresitateressa[Authorize(Roles = "Customers")]
to your action, does the action load? How did you add the user to the role? – TeresitateressaUserRoles
table? Can you verify that the role exists from within the application by running something like(this.RoleManager.FindByNameAsync("Customers").Result != null)
– Teresitateressaand is the role name precisely correct
:P – Teresitateressa