.netasp.net-mvcforms-authenticationformsauthenticationticket

User still not authenticated after AuthCookie is added


I have a pretty normal sign in page, just username and password fields:

<h2>Sign in</h2>

@Html.ValidationSummary()

@using (Html.BeginForm("SignIn"))
{
    <p>
        @Html.LabelFor(model => model.Username)
        @Html.TextBoxFor(model => model.Username)
    </p>
    <p>
        @Html.LabelFor(model => model.Password)
        @Html.PasswordFor(model => model.Password)
    </p>
    <input type="submit" value="Submit"/>
}

I have a sign in action defined like below:

[HttpPost]
[ActionName("SignIn")]
public ActionResult SignInConfirmation(UserCredentialsModel model)
{
    if (ModelState.IsValid)
    {
        var userIsValid = Membership.ValidateUser(model.Username, model.Password);

        if (userIsValid)
        {
            FormsAuthentication.SetAuthCookie(model.Username, false);

            return RedirectToAction("Index", "Home");
        }
        ModelState.AddModelError(string.Empty, "Incorrect username and\\or password.");
    }

    return View();
}   

As well as this I have a partial that will display "Please sign in" or "Welcome user" depending on whether they are authenticated or now.

I can see that the cookie is created and returned, both by debugging the code and via Fiddler.

When the partial is hit though, the user is never authenticated:

[ChildActionOnly]
public ActionResult Index()
{
    if (User.Identity.IsAuthenticated)  // =< This is always false.
    {
        var userDetailsModel = new UserDetailsModel
        {
            UserName = User.Identity.Name
        };

        return PartialView("Authenticated", userDetailsModel);
    }
    return PartialView("Unauthenticated");
}

I've also tried hand rolling an FormsAuthenticationTicket as so:

var userData = JsonConvert.SerializeObject(new { model.Username });
var issueDate = DateTime.Now;
var authenticationTicket = new FormsAuthenticationTicket(1,
    model.Username,
    issueDate,
    issueDate.AddMinutes(5),
    false,
    userData);

but same result...

Why am I never authenticated?


Solution

  • Do you have something like <authentication mode="Forms"> in your web.config You should have it.