Click here to Skip to main content
14,176,277 members
Click here to Skip to main content
Add your own
alternative version

Stats

45.9K views
1.7K downloads
17 bookmarked
Posted 10 Feb 2015
Licenced CPOL

How to Use Form Authentication in ASP.NET and MVC

, 10 Feb 2015
Rate this:
Please Sign up or sign in to vote.
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:

<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.

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:

<asp:LinkButton ID="LinkButton1" runat="server" 

onclick="LinkButton1_Click">Sign Out</asp:LinkButton>

On click event of this Link, get sign out.

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.

<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:

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:

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).

[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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
QuestionAuthorize Pin
htcszgn27-Dec-18 2:35
memberhtcszgn27-Dec-18 2:35 
QuestionRedirect Pin
Member 139377644-Aug-18 2:25
memberMember 139377644-Aug-18 2:25 
QuestionUser's details Pin
Arkadeep De11-Jan-18 7:16
professionalArkadeep De11-Jan-18 7:16 
GeneralMy vote of 3 Pin
Erik Funkenbusch11-Feb-15 5:30
memberErik Funkenbusch11-Feb-15 5:30 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Feb-15 19:44
memberHumayun Kabir Mamun10-Feb-15 19:44 
QuestionAsp.Net Identity Pin
Bob Fayman10-Feb-15 5:49
memberBob Fayman10-Feb-15 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190525.1 | Last Updated 10 Feb 2015
Article Copyright 2015 by Shridhar Gowda
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid