ASP.NET MVC - FormsAuthentication.SetAuthCookie () and RolesIsUserInRole - behavior
Since you are doing this during the login action, it is safe to assume that the user is not logged in yet, and thus User
on HttpContext
(accessible from your controller via this.User
or simply User
) is set for the unauthenticated principal. Roles
will use the current User.Identity.Name
one to get the username and get the roles, so you'll want to use the second overload in this case.
If for some reason you need to use the first overload, you will need to update the user:
User = new GenericPrincipal(new GenericIdentity(user, "forms"), new string[0]);
Usually FormsAuth module will properly update User
the next time you visit the page the user after login, by reading the cookie autorun file, decrypt it and create a new GenericPrincipal
using the FormsIdentity
using the name specified in the ticket.
source to share
var tmp = Roles.IsUserInRole("administrator");
checks if the currently logged in user is in the role, and var _tmp = Roles.IsUserInRole(user, "administrator");
checks if the role is in it user
, regardless of whether they are logged in at the time. And since FormsAuthentication.SetAuthCookie(user, false);
it will not be valid until the next request, user
it is not registered yet.
source to share
SetAuthCookie only sets a cookie. It does not register you or download user information.
the cookie is read in the next request and then ASP.NET will configure roles and identity as part of the request processing pipeline.
You can work around this, but it essentially means duplicating the asp.net authorization code, in just one request. It might be easier to just redirect the user and reload the page.
source to share