I am having a problem with MVC4 user authorization.
System.Web.Security.Membership.ValidateUser
returns true
.
Then it gets to FormsAuthentication.SetAuthCookie
and I see a cookie in my browser.
Then User.Identity.IsAuthenticated
still evaluates to false
for some reason.User.Identity.IsAuthenticated
is still false after a redirect and stays false
.
[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
isauthenticated is False when a user is already logged in.
Identity with a new IIdentity object that will return true from its IsAuthenticated property. Request. IsAuthenticated will then return true . In the case of Forms authentication, the forms authentication module uses the encrypted authentication ticket contained in the authentication cookie to authenticate the user.
Check your webconfig, you have to enable forms authentication:
Add following snippet inside
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="3600" />
</authentication>
Comment out if it is in your webconfig:
<!--<modules>
<remove name="FormsAuthentication" />
</modules>-->
Now you can check
WebSecurity.CurrentUserName, WebSecurity.CurrentUserId and , WebSecurity.IsAuthenticated flags;
User.Identity.IsAuthenticated
won't be set to true until the next request after calling FormsAuthentication.SetAuthCookie()
.
See http://msdn.microsoft.com/en-us/library/twk5762b.aspx
The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false. The forms-authentication ticket supplies forms-authentication information to the next request made by the browser.
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