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;
if (usr == "123" && psswrd == "123")
{
FormsAuthentication.SetAuthCookie(usr, true);
string retrnUrl = Request.QueryString["returnUrl"];
if (!string.IsNullOrEmpty(retrnUrl))
{
FormsAuthentication.RedirectFromLoginPage(usr, Persist.Checked);
}
else
{
Response.Redirect("/HomePage.aspx");
}
}
else
{
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();
}
[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();
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");
}
}
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.