How to use Forms-Based Authentication with MVC4

I am putting this down just to remind myself in the future, since the documentation I've found on-line is very lacking. To add extra context: you don't need anything else to use forms-based authentication.

Most of the documentation you will find on-line will advise you to use some MembershipProvider. You don't need it, and here's how it's done.

What does Forms-Based Authentication do?

Forms-Based Authentication does a few related things.

  1. It writes a cookie which identifies you as, well, yourself. This is done with the static method FormsAuthentication.SetAuthCookie(string, bool). It grabs your HttpResponse and adds its magic cookie. You have to call this method manually once you verify username and password.

  2. For every request, it looks for the magic cookie and reads your username from it. It then sets User.Identity.Name to your name. There's no method to call, but in order to make this happen you need to put stuff in your web.config as such:

    <system.web>
        <authentication mode="Forms" />
    </system.web>
    
  3. It catches when a user tries to access something verboten and redirects them to a chosen login page which you specify in web.config. Example, building on the previous:

    <system.web>
        <authentication mode="Forms">
            <forms loginUrl="/login"/>
        </authentication>
    </system.web>
    
  4. In theory, it tries to redirect the user back to the original verboten page if you set the cookie with FormsAuthentication.RedirectFromLoginPage(string, bool); instead of FormsAuthentication.SetAuthCookie(string, bool). In practice, I couldn't get this to work with MVC4 so I wouldn't count on it.

Practical example

Set up a form passing two strings, username and password to a method called Authenticate (or whatever):

<form action="/authenticate" method="POST">
    <input name="username"/>
    <input type="password" name="password"/>
    <input type="submit"/>
</form>

Create a corresponding method

[HttpPost]
public ActionResult Authenticate(string username, string password)
{
    // You want to have a better method than this to verify credentials!
    if (username == "sklivvz" && password == "sekritz!")
    {
        FormsAuthentication.SetAuthCookie(username, true);
        return Redirect("/");
    }
    return Redirect("~/Content/login.html");
}

Add the magic mantra in web.config:

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="/Content/login.html"/>
    </authentication>
</system.web>

Protect another method with the Attrubute [Authorize]:

[Authorize]
public ActionResult CastSpell()
{
    // Secret magicks here that only wizards may see.
}

That's it. Finito. Happy hacking!


I am the Chief R&D at BaxEnergy, developer, hacker, blogger, conference lecturer. Bio: ex Stack Overflow core, ex Toptal core.

Read more

Newest Posts

I finally emulated my childhood

Last night I decided to dedicate some time to my old [z80 emulator](https://sklivvz.com/posts/z80). I've squashed a few bugs and ported it to .NET 10. Then I added a ULA emulator.

Read more
MoonBuggy: zero-allocation i18n for .NET

Compile-time translations via source generators, ICU MessageFormat + CLDR plurals, PO file workflows, no per-request allocations.

Read more
TDD and the Zero-Defects Myth

TDD can’t guarantee zero-defects. Let us debunk this software development myth.

Read more
What can Stack Overflow learn from ChatGPT?

Stack Overflow could benefit from adopting a using conversational AI to provide specific answers

Read more
Fan mail

Multiple people with my name use my email address and I can read their email, chaos ensues!

Read more

Gleanings

You Are Not Google
Ozan Onay • Jun 07, 2017

Software engineers go crazy for the most ridiculous things. We like to think that we’re hyper-rational, but when we have to choose a technology, we end up in a kind of frenzy 

Read more…