2

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?

2
  • 1
    I would definitely not recommend storing any type of credentials in your web.config on a live site. Commented Oct 4, 2012 at 14:55
  • This is just temporary. I will have a proper implementation later on :) Commented Oct 4, 2012 at 15:21

1 Answer 1

4

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");
}
....
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That worked. I understand now why the SetAuthCookie is required :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.