Practical Demo

Practical Demonstration For Dotnet

My New Blog

Friends and my dudes.. I have altered my blog and change its address to http://www.dotnetandwp7.blogspot.com so please go to that page and refer. In that page i'm going to post Windows phone 7 application development Articles also.. Have a Nice Day....

Friday, July 8, 2011

Form-based Authentication in ASP.NET

It is a common need for a web site to have membership and login system, particularly when part of the web site is restricted in access by non-members. This tutorial will guide you through how to create such a form-based authentication in ASP.NET using C#.

There are totally four things you need to create in order to make a form-based authentication.

1. A database (Access 2000 or SQL server, or any RDBMS with a .NET ODBC driver) with a membership table.

2. A login web control

3. web.config file

4. The actual login page

The membership table

At least you should have a table to store member information. The table can be as simple as having only the MemberID, strUserName and strPassword fields:

-------------

tblMembership

-------------

MemberID

strUserName

strPassword

-------------

You can add any useful fields to this table for your particular need like FirstName, LastName, E-mail address, or even IPAddress for tracking purpose. To keep the problem simple, we will just keep this 3 fields in our discussion.

The login web control

Code for the login web control (login.ascx):
<%@ Control language="C#" %>
<script language="C#" runat="server">
public String BackColor = "#FFFFFF";
public String UserId {
get {
return User.Text;
}
set {
User.Text = value;
}
}

public String Password {
get {
return Pass.Text;
}
set {
Pass.Text = value;
}
}

public String BackGroundColor {
get {
return BackColor;
}
set {
BackColor = value;
}
}

public bool IsValid {
get {
return Page.IsValid;
}
}
</script>
<table style="background-color:<%=BackColor%>
;font: 10pt verdana;border-width:1;
border-style:solid;border-color:black;"
cellspacing=15 ID="Table1">
<tr>
<td><b>Login: </b></td>
<td><ASP:TextBox id="User" runat="server"/></td>
</tr>
<tr>
<td><b>Password: </b></td>
<td><ASP:TextBox id="Pass" TextMode="Password"
runat="server"/></td>
</tr>
<tr>
<td></td>
<td><ASP:Button Text="Submit"
OnServerClick="Submit_Click" runat="server"/></td>
</tr>
<tr>
<td align="center" valign="top" colspan="2">
<asp:RegularExpressionValidator id="Validator1"
ASPClass="RegularExpressionValidator" ControlToValidate="Pass"
ValidationExpression="[0-9a-zA-Z]{5,}"
Display="Dynamic"
Font-Size="8pt"
runat=server>
Password must be >= 5 alphanum chars<br>
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator id="Validator2"
ControlToValidate="User"
Font-Size="8pt"
Display="Dynamic"
runat=server>
UserId cannot be blank<br>
</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="Validator3"
ControlToValidate="Pass"
Font-Size="8pt"
Display="Dynamic"
runat=server>
Password cannot be blank<br>
</asp:RequiredFieldValidator>
</td>
</tr>
</table>


There are a table in which are two textboxes and a button. In order for the password textbox to hide password of the user, we add the TextMode="password" attribute to the password textbox. Note that we have used 3 validator to validates the userName and password: Validator1 and Validator3 validates the password field to check for any empty password or password which are too short. Validator2 check for empty userName.

In this control, I use property to encapsulate any detail of the login control. For a detail discussion on property, read my separate tutorial: Property: Encapsulation in C#

Now, lets see the web.config file.

The web.config file
<configuration>
<system.web>
<customErrors mode="Off"/>
<authentication mode="Forms">
<forms name=".ASPXFORUM"
loginUrl="login.aspx" protection="All"
timeout="30" path="/" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>

What you have to keep watch to is the lines with <authentication> and <authorization> tags.

The mode="Forms" attribute to the authentication tag indicates that form-based authentication is used in the case. The other available attributes are window (for Win NT authentication), passport(for Passport authentication) and none. The protection="All" means both encription and validation-based protection were used. The timeout="30" attribute indicates the cookie expiration period. The path attribute denotes the cookie path. The name attribute is the name of the cookie use. Lastly and the most important one is loginUrl which denotes the login page which will be re-directed to whenever authentication is needed.

For the authorization section, there is only one tag here which is <deny users="?" />. The <deny> tag here specifies that we will deny any un-authenticated user for accessing this directory and any sub-directories where this web.config file is placed. The other tag available is the <allow> tag which would be used to specify what users are allow to access in the current folder and deny access to other user instead.

The login.aspx page

Here is the complete code for the login page:
<%@ Page language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Register TagPrefix="MySite" TagName="Login" Src="login.ascx" %>

<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs E) {
if ((Page.IsPostBack) && (Page.IsValid)) {
string strDSN =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Membership.mdb";
string strSQL = "SELECT userName, userPassword FROM Membership
WHERE userName='" + MyLogin.UserId + "'";

OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
OleDbDataReader dr = null;
try {
myConn.Open();
dr = myCmd.ExecuteReader();

if(dr.Read()) {
if(dr.GetString(1).Trim() == MyLogin.Password.Trim()) {
FormsAuthentication.RedirectFromLoginPage(MyLogin.UserId, false);
}
else
Message.Text = "Sorry! Your login or password is incorrect.
<br>Please log in again.";
}
else
{
Message.Text = "Sorry! Your login or password is incorrect.
<br>Please log in again.";
}
}
catch(Exception myException) {
Response.Write("Oops. The error: " + myException.Message);
}
finally {
myConn.Close();
}
}
}
</script>
<html>
<body>
<h3>Login</h3>
<form runat="server" ID="Form1">
<asp:Label id="Message" runat="server" />
<MySite:Login id="MyLogin" BackColor="#FFFFCC" runat="server"/>
</form>
</body>
</html>


What you need to observe in this snipplet of code is the namespaces which need to be imported and the use of a web control by using the Register directive. The TagPrefix attribute is the prefix you use to specify this user control instead of the asp: tag prefix to use with web controls. TagName is the tag you use and src points to the source code of the actual user control which we had discussed before.

The database connection codings here is quite trivial, it simply query the table and see whether the user name exists in the table. If yes, the password is checked, otherwise, an error message is delivered.

The worth-noting line is:
FormsAuthentication.RedirectFromLoginPage(MyLogin.UserId, false);


This line will redirect the user to the page where he/she originally requested if he/she is successfully authenticated. The false at the end indicates that persistent cookie is not used in this case. Turn it to true if you need to use persistent cookie.

No comments:

Post a Comment

Introduction to DotNet ...

.NET framework is an essential component of the windows operating system and helps create applications by integrating different programming languages, such as Visual C#, Visual Basic, Visual C++, and so on. .NET Framework consists of a virtual execution syatem called the common language runtime(CLR) and a set of class libraries. CLR is a Microsoft product of the Common Language Infrastructure(CLI), which is an industrial standard and a basis for creating execution and development environmentss in which languages and libraries work together. Microsoft introduced .NET to bridge the gap and ensure interoperability between application created in different languages. .NET framework is used to integrate the business logic of an application implemented in different programming languages and services. Consequently, it induces significant improvements in code reusability, code specialization, resource management, development of applications in multiple programming languages, security, deployment, and administration of programs developed in multiple programming languages..

Why .NET?

Why .NET? Mainly .NET is the competitor for JAVA. . Its an environment or platform. It contains collection of services for application development and application execution. It supports different type of applications development. ex: CUI, GUI, console, web based,mobile applications Main thing is .NET is network & Internet based application development.It provides a good development environment. ex: Drag and Drop design - IntelliSense features - Syntax highlighting and auto-syntax checking - Excellent debugging tools - Integration with version control software such as Visual Source Safe (VSS) - Easy project management

Evaluation of .NET:

Around 1995, Java was gaining popularity because of its platform-independent approach and Sun Microsyatem's open source policy. Later in 2002, Sun Microsystems released the enterprise edition of Java. ie., Java 2 Enterprise edition(J2EE), which is a Java Platform to develop and execute distributed Java Applications based on the N-tier architecture. The advent of J2EE eventually led to the decline of, Microsoft's Market share. Consequently, Microsoft started a project called NEXT GENERATION WINDOWS SERVICE(NGWS) to regain the market share . It tooks more than three years to develop the product, Which is Known as .NET. Microsoft released the first version of .NET with the name .NET Framework 1.0 on february 13,2002, along with the Visual studio .NET 2002 integrated development environment(IDE). .NET's Second revised version took nearly a year to release; and it was known as .NET framework 1.1 Microsoft Visual studio .NET, bettre known as Visual studio .NET2003, was also a part of the second release. The next version of .NET framework, .NET Framework 2.0, was released with Visual studio .NET 2005 on november 07,2005. .NET framework 3.0 formerly called WinFX, was released on novenber 06,2006. Finally the latest version of .NET framework, known as .NET framework 3.5, was released with Visual studio .NET2008 on november 19,2007.

Flavors of .NET:


Contrary to general belief .NET is not a single technology. Rather it is a set of
technologies that work together seamlessly to solve your business problems. The
following sections will give you insight into various flavors and tools of .NET and what kind of applications you can develop.
• What type of applications can I develop?
When you hear the name .NET, it gives a feeling that it is something to do only with internet or networked applications. Even though it is true that .NET provides
solid foundation for developing such applications it is possible to create many other types of applications. Following list will give you an idea about various
types of application that we can develop on .NET.
1. ASP.NET Web applications:
These include dynamic and data driven browser
based applications.
2. Windows Form based applications:
These refer to traditional rich client applications.
3. Console applications:
These refer to traditional DOS kind of applications like
batch scripts.
4. Component Libraries:
This refers to components that typically encapsulate
some business logic.
5. Windows Custom Controls:
As with traditional ActiveX controls, you can develop your own windows controls.
6. Web Custom Controls:
The concept of custom controls can be extended to
web applications allowing code reuse and modularization.
7. Web services:
They are “web callable” functionality available via industry standards like HTTP, XML and SOAP.
8. Windows Services:
They refer to applications that run as services in the
background. They can be configured to start automatically when the system boots up.
As you can clearly see, .NET is not just for creating web application but for almost all kinds of applications that you find under Windows.

Feature Of .NET

Features of .NET

Now that we know some basics of .NET, let us see what makes .NET a wonderful

platform for developing modern applications.

• Rich Functionality out of the box

.NET framework provides a rich set of functionality out of the box. It contains hundreds of classes that provide variety of functionality ready to use in your applications. This means that as a developer you need not go into low level details

of many operations such as file IO, network communication and so on.

Easy development of web applications

ASP.NET is a technology available on .NET platform for developing dynamic and data driven web applications. ASP.NET provides an event driven programming model (similar to Visual Basic 6 that simplify development of web

pages (now called as web forms) with complex user interface. ASP.NET server controls provide advanced user interface elements (like calendar and grids) that save lot of coding from programmer’s side.

• OOPs Support

The advantages of Object Oriented programming are well known. .NET provides a fully object oriented environment. The philosophy of .NET is – “Object is mother of all.” Languages like Visual Basic.NET now support many of the OO

features that were lacking traditionally. Even primitive types like integer and characters can be treated as objects – something not available even in OO languages like C++.

• Multi-Language Support

Generally enterprises have varying skill sets.
For example, a company might have people with skills in Visual Basic, C++, and Java etc. It is an experience that
whenever a new language or environment is invented existing skills are outdated.

This naturally increases cost of training and learning curve. .NET provides something attractive in this area. It supports multiple languages. This means that if you have skills in C++, you need not throw them but just mould them to suit
.NET environment. Currently four languages are available right out of the box namely – Visual Basic.NET, C# (pronounced as C-sharp), Jscript.NET and
Managed C++ (a dialect of Visual C++). There are many vendors that are working on developing language compilers for other languages (20+ language compilers are already available). The beauty of multi language support lies in the
fact that even though the syntax of each language is different, the basic capabilities of each language remain at par with one another.

• Multi-Device Support

Modern lift style is increasingly embracing mobile and wireless devices such as PDAs, mobiles and handheld PCs. . . .NET provides promising platform for programming such devices. .NET Compact Framework and Mobile Internet Toolkit are step ahead in this direction.

• Automatic memory management

While developing applications developers had to develop an eye on system resources like memory. Memory leaks were major reason in failure of applications. .NET takes this worry away from developer by handling memory on its own. The garbage collector takes care of freeing unused objects at appropriate intervals.

• Compatibility with COM and COM+

Before the introduction of .NET, COM was the de-facto standard for componentized software development. Companies have invested lot of money and efforts in developing COM components and controls. The good news is – you can still use COM components and ActiveX controls under .NET. This allows you to use your existing investment in .NET applications. .NET still relies on COM+ for features like transaction management and object pooling. In fact it provides enhanced declarative support for configuring COM+ application right from your source code. Your COM+ knowledge still remains as a valuable asset.

• No more DLL Hell

If you have worked with COM components, you probably are aware of “DLL hell”. DLL conflicts are a common fact in COM world. The main reason behind this was the philosophy of COM – “one version of component across machine”.

Also, COM components require registration in the system registry. .NET ends this DLL hell by allowing applications to use their own copy of dependent DLLs.

Also, .NET components do not require any kind of registration in system registry.

• Strong XML support

Now days it is hard to find a programmer who is unaware of XML. XML has gained such a strong industry support that almost all the vendors have released some kind of upgrades or patches to their existing software to make it “XML compatible”. Currently, .NET is the only platform that has built with XML right into the core framework. .NET tries to harness power of XML in every possible way. In addition to providing support for manipulating and transforming XML
documents, .NET provides XML web services that are based on standards like HTTP, XML and SOAP.

• Ease of deployment and configuration

Deploying windows applications especially that used COM components were always been a tedious task. Since .NET does not require any registration as such,
much of the deployment is simplified. This makes XCOPY deployment viable.

Configuration is another area where .NET – especially ASP.NET – shines over traditional languages. The configuration is done via special files having special
XML vocabulary. Since, most of the configuration is done via configuration files,

there is no need to sit in front of actual machine and configure the application manually. This is more important for web applications; simply FTPing new configuration file makes necessary changes.

• Security

Windows platform was always criticized for poor security mechanisms. Microsoft has taken great efforts to make .NET platform safe and secure for enterprise applications. Features such as type safety, code access security and role based
authentication make overall application more robust and secure.