Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User.Identity.IsAuthenticated returns false after setting cookie and validating

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);
}
like image 837
coryrwest Avatar asked Jan 24 '13 18:01

coryrwest


People also ask

Why is user identity IsAuthenticated false?

isauthenticated is False when a user is already logged in.

How does request IsAuthenticated work?

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.


2 Answers

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;

like image 123
Nalan Madheswaran Avatar answered Sep 16 '22 15:09

Nalan Madheswaran


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.

like image 39
jrummell Avatar answered Sep 20 '22 15:09

jrummell