Search code examples
c#asp.netasp.net-mvcmembership

ASP.NET MVC3 User Login


I have a User model with:

[Required]
public string Password { get; set; }

[Required]
public string UserName { get; set; }

I have a MyMembershipProvider : MembershipProvider containing:

public override bool ValidateUser(string username, string password)
{
   if (username == ConfigurationManager.AppSettings["DefaultUsername"] && password == ConfigurationManager.AppSettings["DefaultUserPassword"])
   {
       return true;
   }
   else
   {
       return false;
   }
}

My LogOn action looks like:

[HttpPost]
    public ActionResult LogOn(User model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                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);
    }

The Problem:

When I specify the correct username and password, I can't seem to go to actions and controllers which contain the [Authorize] attribute. When I use breakpoint, it DOES fall in to return RedirectToAction("Index", "Home"); but denies access to the Index page.

Can anyone see where I am going horribly wrong?


Solution

  • You need to set the auth cookie so the next action recognises that the user is authenticated.

    ....
    if (Membership.ValidateUser(model.UserName, model.Password))
    {
        FormsAuthentication.SetAuthCookie(model.UserName, true);
        return RedirectToAction("Index", "Home");
    }
    ....