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!


Hi, I'm Marco Cecconi. I am the founder of Intelligent Hack, developer, hacker, blogger, conference lecturer. Bio: ex Stack Overflow core team, ex Toptal EM.

Read more

Newest Posts

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
Intelligent Trip

After years of building, our top-notch consultancy to help start-ups and scale-ups create great, scalable products, I think it is high time I added an update to how it is going and what's next for us.

Read more
Guest blog: Building, in partnership with communities by Shog9

A lesson in building communities by Stack Overflow's most prominent community manager emeritus, Shog9

Read more
Can you migrate a company from on-premise to remote-only?

Some lessons learned over the past 8 years of remote work in some of the best remote companies on the planet

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…