I have something like this:
FormsAuthentication.SetAuthCookie(user, false);
var tmp = Roles.IsUserInRole("administrator");
var _tmp = Roles.IsUserInRole(user, "administrator");
tmp is always false, and _tmp is always true. Why is tmp false?
Since you are doing this during a login action, it's safe to assume the user is not logged in yet, and thus the User on HttpContext (accessible from your controller via this.User or just User) is set to an unauthenticated principal. Roles will use the current User.Identity.Name to get the username and retrieve roles, so in this case, you'd want to use the second overload.
If you need to use the first overload for some reason, you'd have to update user:
User = new GenericPrincipal(new GenericIdentity(user, "forms"), new string[0]);
Normally, the FormsAuth module would update the User appropriately the next time the user visits a page after logging in, by reading the auth ticket cookie, decrypting it, and creating a new GenericPrincipal with a FormsIdentity using the name found in the ticket.
var tmp = Roles.IsUserInRole("administrator"); is checking if the currently logged in user is in the role while var _tmp = Roles.IsUserInRole(user, "administrator"); is checking if user is in the role, whether or not they are logged in at the time. And since FormsAuthentication.SetAuthCookie(user, false); won't take effect until the next request, user isn't actually loggen in yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With