Wednesday, November 2, 2011

Securing ASP.Net Pages - Forms Authentication - C# and .Net 4

ASP.Net has a built-in feature named Forms Authentication that allows a developer to easily secure certain areas of a web site. In this post I'm going to build a simple authentication sample using C# and ASP.Net 4.0 (still in beta as of the posting date).
Security settings with ASP.Net is configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file:

configuration>
system.web>
authenticationmode="Forms">
formsname="TestAuthCookie"loginUrl="login.aspx"timeout="30">
credentialspasswordFormat="Clear">
username="user1"password="pass1"/>
username="user2"password="pass2"/>
>
>
>
authorization>
denyusers="?"/>
>
compilationtargetFramework="4.0"/>
pagescontrolRenderingCompatibilityVersion="3.5"clientIDMode="AutoID"/>
>
>
Here is the complete source of the sample login.aspx page:
div>
Username:
asp:TextBox ID="txtUsername" runat="server">:TextBox>
Password:
asp:TextBox ID="txtPassword" runat="server">:TextBox>
asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" />
asp:Label ID="lblStatus" runat="server" Text="Please login">:Label>
/div>


And here is the complete source of the login.aspx.cs file:
using System;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Default3 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
{
lblStatus.Text = ("Welcome " + txtUsername.Text);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
else
{
lblStatus.Text = "Invalid login!";
}

}
}