ASP.NET MVC - FormsAuthentication.SetAuthCookie() and RolesIsUserInRole - wierd behavior

ojek picture ojek · Jan 29, 2013 · Viewed 7.3k times · Source

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?

Answer

moribvndvs picture moribvndvs · Jan 29, 2013

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.