The reason your code does not work as expected is because User has technically not and is not yet signed. What, what? But you called SignIn!
FormsAuth.SignIn(userName, rememberMe); - which in this case is just a wrapper for FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); - only sets the asp.net authorization cookie in the users browser as part of the response. Only for requests after this item indicates that the user's browser will have a cookie, as a result of which the asp.net member will correctly configure the User object. All your code in the LogOn method still accepts an anonymous user, so the IsInRole check fails and you are redirected home. Place the if statement on another page and after logging in you will see that User.IsInRole now works as expected. (And really, this is what you would use User.IsInRole for, just not during the login process)
So how to check during the actual login process? Roles.IsUserInRole or Roles.GetRolesForUser are several ways, for example:
if (Roles.IsUserInRole(userName, "Administrator") || Roles.IsUserInRole(userName, "Administrator")) { return RedirectToAction("Index", "AdminApp"); }
You must explicitly specify the login name of the user who logs in to the membership data warehouse. In this note, I believe that the above code would lead to two requests being executed, which might turn out to be less than ideal. This is where Roles.GetRolesForUser might be the best option:
string[] roles = Roles.GetRolesForUser(userName); if (roles.Contains("Administrator") || roles.Contains("Manager")) { return RedirectToAction("Index", "AdminApp"); }
Hope this helps!
Kurt schindler
source share