APEXA, LLC
Blog Gallery Contact

ASP.NET MVC Login complete Forms Authentication

Blog Date: Friday, March 19, 2010 - Discuss below!

 Recent Blogs << Back

What is Microsoft .NET and How does it work? 3/9/2010

C# - Writing your own .NET Compiler 3/10/2010

Unable to open the Outlook window; MS solution bad 3/16/2010

 More...
 

IT Jobs Hiring


Cisco Voice Operations Engineer New York, NY

Sr. Software Engineer -- DSP Algorithms, Security Encryption, C/C++ (San Diego, CA ) Los Angeles Area, CA

PHP Programming -- XAMPP (Beverly Hills) Los Angeles Area, CA

More jobs...
 

I'm always trying to find a quick way to get Forms Authentication to work completely with ASP.NET. This is a quick simple example of how to implement it in ASP.NET MVC project. Go ahead and copy the code if you want to get it up and working in your project really quickly

Web.Config | View | Model | Controller :

Web.Config - Web.Config | View | Model | Controller

<authentication mode="Forms">
  <forms timeout="2880" loginurl="~/Account/Login"></forms>
</authentication>

View (ASP.NET) - Web.Config | View | Model | Controller

<h2>Login</h2>
<p>
    Please enter your username and password.
</p>

<% using (Html.BeginForm()) { %>
    <%= Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
    <div>
        <fieldset>
            <legend>Account Information</legend>
            
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Username) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Username) %>
                <%= Html.ValidationMessageFor(m => m.Username) %>
            </div>
            
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Password) %>
            </div>
            <div class="editor-field">
                <%= Html.PasswordFor(m => m.Password) %>
                <%= Html.ValidationMessageFor(m => m.Password) %>
            </div>
            
            <div class="editor-field editor-group">
                <%= Html.RadioButton("CategoryID", 2, true, new { @id = "Customer" }) %>
                <%= Html.Label("Customer") %>
                <%= Html.RadioButton("CategoryID", 1, new { @id = "Employee" })%>
                <%= Html.Label("Employee")%>
            </div>
            
            <div class="editor-label">
            <input type="submit" value="Login" />
                <%= Html.CheckBoxFor(m => m.RememberMe) %>
                <%= Html.LabelFor(m => m.RememberMe) %>
            </div>
        
            
            
        </fieldset>
    </div>
<% } %>

Model - Web.Config | View | Model | Controller

I actually implemented it as a ViewModel because that is what I use exclusively in MVC. For more information on ViewModel design (MVVM architecture, take a look at this: )

public class LoginViewModel
{
    [Required(ErrorMessage="Username is required to login.")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Password is required to login.")]        
    public string Password { get; set; }
    
    public int CategoryID { get; set; }
    
    public bool RememberMe { get; set; }
}

Controller - Web.Config | View | Model | Controller

[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        // Get a manager
        IUserManager manager = ManagerFactory.Create(this._repository, model.CategoryID);

        // Get user info
        var user = manager.Authenticate(model.Username, model.Password);
        if (user != null && user.UserID > 0)
        {
            persistUser(user, model.RememberMe);

            return Redirect("Home/Index?msg=" + Server.HtmlEncode(
                string.Format("Successfully logged in user \"{0} {1}\"",
                user.FirstName, user.LastName)));
        }
        else
        {
            ViewData["Message"] = string.Format(
                "Invalid username/password combination. Please try again.");

            return View(model);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

private void persistUser(UserInfo user, bool rememberMe)
{
    // Create ticket
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1,
        "user",
        DateTime.Now,
        DateTime.Now.AddMinutes(3),
        true,
        "fabiano!",
        FormsAuthentication.FormsCookiePath);

    // Create encrypted cookie
    string hash = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }

    // Set and done
    Response.Cookies.Add(cookie); //Necessary, otherwise UserData property gets lost
}

So there you have it. It persists your FormsAuth cookie across sessions. Although you can go and modify it once you have it working :)



Monday, March 22, 2010 5:11:16 PM

Home | Gallery | Contact | IT Consulting | Web Marketing | Search Engine Optimization | Web Design & CMS | My Blog on C# .NET

Site Map | Copyright 2007 Web Design web design | Developed by APEXA, LLC

APEXA, LLC