Search code examples
c#asp.netasp.net-mvc-3membership

Any tutorials on creating an MVC3 login system without the default ASP.Net membership providers?


I'm looking for a tutorial or small introductory guide on creating a login system for ASP.Net MVC3 without using the default ASP.Net membership provider.

I've created a new MVC3 project with the Internet Application template, and here is the contents of _LogOnPartial.cshtml:

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}

Is @User.Identity.Name part of the membership provider? I'd like to read some more on membership on ASP.Net MVC3, since I already have a database in place with user credentials, I do not need the prapackaged one.

Thank you!


Solution

  • Its actually fairly easy to implement custom authentication code in ASP.NET MVC.

    In the LogOn method of your controller you'll need to call the FormsAuthentication provider after you have authenticated the user's credentials.

    public ActionResult LogOn(LogOnModel model)
    {
       //Handle custom authorization then call the FormsAuthentication provider
    
       FormsAuthentication.SetAuthCookie(/*user name*/, true);
    
       //Return view
    }
    

    After this method call, The User.Identity.Name will be populated, and you can utilize the AuthorizeAttribute on your controllers or controller methods.

    In the LogOff method of your controller you'll call the FormsAuthentication provider again

    public ActionResult LogOff()
    {
       FormsAuthentication.SignOut();
    
       //Return view
    }