Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Use Form Authentication in ASP.NET and MVC

0.00/5 (No votes)
10 Feb 2015 1  
This tip will give you a knowledge of how to implement form authentication in classic ASP.NET and ASP.NET MVC. I am sure you will have considerable knowledge after reading this tip.

Introduction

This tip is targeting beginner and intermediate programmers. Just download the source code and run on your machine. It's developed in ASP.NET 4.0. This tip will give you a knowledge of how to implement form authentication in classic ASP.NET and ASP.NET MVC. I am sure you will have commandable knowledge after reading this tip.

Using the Code for ASP.NET

Add a web page, name it as LoginPage.aspx. Add two text boxes, one for User name and one for Password. Add a Check box for "Remember me?" facility. Add a button to submit credentials. Your HTML should look something like this:

HTML
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:CheckBox Text="Remember me?" ID="Persist" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>

In the server side page LoginPage.aspx.cs, add this code in login button click event.

C#
protected void Button1_Click(object sender, EventArgs e)
        {
            string usr = TextBox1.Text.Trim().ToUpper();
            string psswrd = TextBox2.Text;
            
            //Verify the credentials against database. Here I hard coded for simplicity.
            if (usr == "123" && psswrd == "123")
            {
                FormsAuthentication.SetAuthCookie(usr, true);
                string retrnUrl = Request.QueryString["returnUrl"];
                if (!string.IsNullOrEmpty(retrnUrl))
                {
                    //Redirect to Original requested page
                    FormsAuthentication.RedirectFromLoginPage(usr, Persist.Checked);
                }
                else
                {
                    //If user directly opened login page, always show him Homepage.
                    Response.Redirect("/HomePage.aspx");
                }
            }
            else
            {  
                //If Credentials are wrong, show him error message.
                Label1.Text = "User name or password is wrong";
                Label1.ForeColor = Color.Red;
            }
        }

Create a User control for sign out facility. Register this User control on every web page except Login Page. HTML of User control is:

HTML
<asp:LinkButton ID="LinkButton1" runat="server" 
onclick="LinkButton1_Click">Sign Out</asp:LinkButton>

On click event of this Link, get sign out.

C#
protected void LinkButton1_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("/LoginPage.aspx");
        }

You are done!

Run your application and see how it is working.

Using the Code for MVC

Create a MVC project.

Add this settings in web.config.

XML
<authentication mode="Forms">
      <forms loginUrl="~/Login/Login" timeout="2880" />
    </authentication>
    <authorization>
      <allow users="*"/>
      <deny users="?"/>
    </authorization>

Add a model for user credential structure like below:

C#
public class User
    {
        [Required]
        [RegularExpression("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")]
        public string UserName { get; set; }

        [Required]
        public string passWord { get; set; }        
    }

Create a Controller to handle Login event:

C#
public class LoginController : Controller
    {
        public ActionResult Login()
        {   
            return View();
        }
        
        //User is the model. and value for returnUrl will be automatically received by this action.
        [HttpPost]
        public ActionResult Login(User u, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                string struName = Convert.ToString(u.UserName).ToUpper().Trim();
                string strPassword = Convert.ToString(u.passWord).ToUpper().Trim();

                //Verify credentials against database in real project
                if (struName == "123@123.com".ToUpper() && strPassword == "123".ToUpper())
                {
                    FormsAuthentication.SetAuthCookie(u.UserName.ToUpper(), false);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("details", "Test");
                    }
                }
                else
                {
                    ModelState.AddModelError("authenticationError", 
            "User name or Password is wrong. Try it again");
                    //lblError.Text = "User name or Password is wrong. Try it again";
                }
            }
            return View(u);
        }

        [Authorize]
        [HttpGet]
        public ActionResult logOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");

        }

Now, add a view with two text boxes for user name and password. One submit button. You are done with login view.

Now let us test it.

Add another controller named testController. Two action methods Index and Default. Add two views corresponding to these action methods. Importantly, Add [Authorize] attribute over Controller (or you can add it to specific action methods).

C#
[Authorize]
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ViewResult details()
        {
            return View();
        }     
    }

Now execute the application and try to access "Test/Index" action in URL. You will be redirected to Login view. If and only if you are authenticated, Index views will be shown. :)

Note: You can add jquery.validate.unobtrusive.js file in login view to show ValidationSummary if credential is wrong.

Hurray!!

And don't forget to rate this tip and leave a comment.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here