Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 789
ojek Avatar asked Nov 30 '25 04:11

ojek


2 Answers

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.

like image 97
moribvndvs Avatar answered Dec 02 '25 16:12

moribvndvs


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.

like image 22
Forty-Two Avatar answered Dec 02 '25 16:12

Forty-Two