Roman Pushkin
Roman Pushkin

Reputation: 6111

Simplest authentication for ASP.NET MVC3

I've stuck with simple thing :(

I have an ASP.NET MVC3 app with /Admin/ URL. I put [Authorize] attribute there, it's OK with that. But now I need simple thing: just to limit access to it with only one username/password.

I don't want create database with ASP.NET forms authorization, and I need it to work on my development PC with Visual Studio, and IIS7 server.

What's the best way to do this fast? What I have to put to web.config to make it work with "admin/p4ssw0rd" pair?

Upvotes: 0

Views: 311

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

When you created the ASP.NET MVC 3 application, Visual Studio added an AccountController. Simply modify the LogOn action so that instead of looking in database you perform the verification manually:

public class AccountController : Controller
{

    ...

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // Here you can check the username and password against any data
            // store you want
            if (model.UserName == "admin" && model.Password == "p4ssw0rd")
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    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);
    }

    ...

}

Upvotes: 1

Maayan Glikser
Maayan Glikser

Reputation: 873

see: this question

You can specify your username and password explicitly (please note the solution if you wish to use the password in plain text.

Upvotes: 2

Related Questions