Wednesday, 27 July 2011

Forms authentication using ASP.NET 2.0 and C#.NET


Forms authentication enables user and password validation for Web applications that do not require Windows authentication. With forms authentication, user information is stored in an external data source. You can require that all requests to an application contain a valid user authentication ticket by using the authorization configuration element to deny the request of any unknown user.

In this tutorial, the only configuration step beyond that is to add the following code in the web.config file, inside the <system.web> element.

<authentication mode="Forms">
<forms name=".SecurityDemo" loginUrl="LoginVerifyCsharp.aspx">
<credentials passwordFormat="Clear">
<user name="John" password="Foo"/>
<user name="Mary" password="Bar"/>
</credentials>

</forms>
</authentication>

<machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate"/>
<authorization>
<deny users="?"/>
</authorization>

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

First, Forms authentication enables user and password validation for Web applications that do not require Windows authentication. With forms authentication, user information is stored in an external data source. You can require that all requests to an application contain a valid user authentication ticket by using the authorization configuration element to deny the request of any unknown user. In order to validates a user name and password against credentials stored in the configuration file for an application, we using FormsAuthentication.Authenticate Method. And we use  the btnLoginBetter_Click to do the work. We then call  the Class FormsAuthentication to use the Properties of  FormsCookiePath, Path, Expires and the methods of Encrypt.  And then the we use FormsAuthenticationTicket class to create an object that represents the authentication ticket that is used by forms authentication to identify an authenticated user. The properties and values of a forms-authentication ticket are converted to and from an encrypted string that is stored in a cookie or in the URL. The Cookie class is used by a client application to retrieve information about cookies received with HTTP responses. The following cookie formats are supported during parsing the HTTP response headers.

public partial class Login_VerifyCsharp : System.Web.UI.Page
{
protected void btnLoginBetter_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(tbName.Text, tbPass.Text))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.tbName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), this.PersistCookie.Checked, "User");
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
if (this.PersistCookie.Checked)
{
cookie.Expires = ticket.Expiration;
}
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
lbUser.Text = "The UserName is " + tbName.Text;
if (tbName.Text == "John")
{
lbSf.Text = "The Role is " + "admin";
}
else
{
lbSf.Text = "The Role is " + "user";
}
FormsAuthentication.RedirectFromLoginPage(tbName.Text, false);
}
else
{
Response.Write("<script>alert('Error!')</script>");
}
}

protected void Page_Load(object sender, EventArgs e)
{

}
}

We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!

The front end Default.aspx page looks something like this:

<asp:label id="Label1" runat="server">UserName:</asp:label>&namp;bsp; &nbsp;<asp:textbox id="tbName" runat="server" Width="183px"></asp:textbox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="tbName"
ErrorMessage="Please Input UserName!!!"></asp:RequiredFieldValidator><br />
<br />
<asp:label id="Label2" runat="server" Width="78px">PassWord:</asp:label>
<asp:textbox id="tbPass" runat="server" Width="183px"></asp:textbox>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Is Save Cookie:" Width="98px"></asp:Label>
<asp:checkbox id="PersistCookie" runat="server"></asp:checkbox><br />
<br />
<asp:Button ID="btnLoginBetter" runat="server" OnClick="btnLoginBetter_Click" Text="Log"
Width="99px" /><br />
<br />
<asp:Label ID="lbUser" runat="server" Width="286px"></asp:Label><br />
<br />
<asp:Label ID="lbSf" runat="server" Width="287px"></asp:Label>

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login_VerifyCsharp : System.Web.UI.Page
{
protected void btnLoginBetter_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(tbName.Text, tbPass.Text))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.tbName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), this.PersistCookie.Checked, "User");
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
if (this.PersistCookie.Checked)
{
cookie.Expires = ticket.Expiration;
}
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
lbUser.Text = "The UserName is " + tbName.Text;

if (tbName.Text == "John")
{
lbSf.Text = "The Role is " + "admin";
}
else
{
lbSf.Text = "The Role is " + "user";
}
}
else
{
Response.Write("<script>alert('Error!')</script>");
}
}

protected void Page_Load(object sender, EventArgs e)
{

}
}

Looking for the VB 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment