CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Implementing Forms Authentication in ASP.Net 2.0

By Satheesh babu
Posted On Aug 13,2008
Article Rating:
Be first to rate
this article.
No of Comments: 5
Category: ASP.Net
Print this article.

Implementing Forms Authentication in ASP.Net 2.0

Introduction

Any ASP.NET site we develop will always have an authentication module unless and until there is nothing private on the site or something we explicitly know as being unnecessary. For instance, a simple public content site will not require an authentication module. Depending on the nature of the application we can decide on the type of authentication we are going to provide for our site. Means, if it is going to be an intranet web application, then we can very well utilize the windows authentication by making use of the availability of user information in the AD thus preventing a separate user information storage private to our application. If our application is an internet application, then the best choice is to use Forms Authentication.

From 1.x days, the implementation of forms authentication in ASP.Net is not that much complicated. But the actual drawbacks are, in those days, ASP.Net itself does not have that many controls that aid in implementing forms authentication easily. With the introduction of 2.0, we have a handful of controls that helps in implementing based forms authentication very easy with the primary support of Providers in ASP.Net 2.0. This article will explore the implementation forms authentication using ASP.Net 2.0. Also, We will use some of the login controls to achieve some of the tasks very easily.


Who process the FormsAuthentication?

Forms authentication is processed by a HTTP module called FormsAuthenticationModule which takes part in regular ASP.net page processing.

 

Login Controls and Providers

This section will help us understand on how much suitable are these Login controls to use in our projects. As I said earlier, ASP.Net 2.0 is packed with a set of new controls called Login controls through which we can implement forms authentication with very less effort. By default, Login controls will use the default membership provider and role provider which will have their own database schema. So, it is not advisable to use this controls as it is because enterprise applications itself will have its own database schema and architecture. Solution for this problem is to develop our own custom provider or our own custom code that solves our application specific requirements. In this article, I will explain our subject matter with a custom implemented login form without using any providers. Also, we will have a look on how some of the login controls can be used effectively when using forms authentication.

 

Implementation of Login Form

1.      Drag 2 textboxes, txtUname and txtPass. Drag a button and name it as btnLogin.

Login.aspx

       <table>

            <tr>

                <td style="width: 100px">

                    UserName</td>

                <td style="width: 100px">

        <asp:TextBox ID="txtUname" runat="server"></asp:TextBox></td>

            </tr>

            <tr>

                <td style="width: 100px">

                    Password</td>

                <td style="width: 100px">

        <asp:TextBox ID="txtPass" runat="server"></asp:TextBox></td>

            </tr>

            <tr>

                <td style="width: 100px">

                </td>

                <td style="width: 100px">

        <asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Login" /></td>

            </tr>

            <tr>

                <td style="width: 100px">

                </td>

                <td style="width: 100px">

                    <asp:Label ID="lblMessage" runat="server"></asp:Label></td>

            </tr>

        </table>

 

2.      On btnLogin button click,

 

protected void btnLogin_Click(object sender, EventArgs e)

    {

        string pass = CheckUser(txtUname.Text);

        if (pass == null | pass == "")

        {

            lblMessage.Text = "Not a valid user!";

            return;

        }

        if (txtPass.Text == pass)

        {

            FormsAuthentication.RedirectFromLoginPage(txtUname.Text, false);

        }

        else

        {

            lblMessage.Text = "Wrong Password!";

        }

    }

    public string CheckUser(string UserID)

    {

        string Password = null;

        con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL Connection String"].ConnectionString);

        con.Open();

        com = new SqlCommand(SP_CHECKUSER, con);

        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.Add("@UserId", DbType.String).Value = UserID;

        dr = com.ExecuteReader();

        while (dr.Read())

        {

            Password = dr["Password"].ToString();           

        }

        return Password;

    }

If the authentication is successful, the user will be automatically redirected to the page which he is trying to access initially. The parameter “false” in the method RedirectFromLoginPage(txtUname.Text, false) indicates the cookie generated will be non-persistent cookie.

 

3.      Configure Forms Authentication in Web.Config.

    <authentication mode="Forms">

      <forms loginUrl="Login.aspx"/>

    </authentication>

    <authorization>

      <deny users="?"/>

    </authorization>

If we execute the application, it will automatically redirect to Login.aspx to authenticate. If we see the above config setting, we are denying anonymous access; hence, the users trying to access any resource in the website will be automatically redirected to the Login.aspx page. Read more about the <authentication> tag by visiting the link given in Reference section of this article. The drawback of this above approach, it is not possible to access any page in the website without authenticating. But, if we see most of the sites they will allow access to certain resources like home page, etc without authenticating. The next section will help us doing the same.

 




Allowing Access to certain sections without Authentication

For example, if we want to allow access to certain resources like Home page it can be achieved through <location> tag in Web.Config.

The syntax of this tag is,

  <location path="Path">

    <system.web>

      <authorization>

        //Restrict Access

      </authorization>

    </system.web>

  </location>

This <location> element should be kept outside <System.Web> element in Web.Config. To allow access to Home page without authentication the location tag will be,

<location path="Home.aspx">

    <system.web>

      <authorization>

        <allow users="*"/>

      </authorization>

    </system.web>

  </location>

If we specify a folder name in the path attribute, it will allow/deny access to all the resources inside the folder depending upon the authorization rules given inside <authorization> tag.

For example,

  <location path="Articles">

    <system.web>

      <authorization>

        <deny users="?"/>

      </authorization>

    </system.web>

  </location>

This will deny users to access folders inside “Articles” folder without authentication.

 

Adding Remember Me Option

In btnLogin_Click event, the line that redirects to original page which the user is requesting has an argument for specifying cookie, as persistent or non persistent cookie. This attribute is the one that is used for “Remember Me” option in Login pages. Include a Checkbox beneath the password textbox in the login page and assign the Checked property of the checkbox as the value for the above said argument.

 

FormsAuthentication.RedirectFromLoginPage(txtUname.Text, chkRemember.Checked);

 

In the next section, we will see how to use the LoginView control to show and hide a group of controls on a page based on the authentication status.

 

Using LoginView Control

Sometimes, we will be required to show/hide a control or group of control based on the login status of the user. Means, we can show a particular control only if the user is logged in and hence it prevents a user to do some operations without logging in. This is the use of LoginView Control.

It can be used to show or hide a group of control or content based on the user login status.

Below is the syntax of using it.

<asp:LoginView ID="LoginView1" runat="server">

    <LoggedInTemplate>

    </LoggedInTemplate>

    <AnonymousTemplate>

    </AnonymousTemplate>

</asp:LoginView>

Things inside <LoggedInTemplate> will be exposed only if the user is already logged in where the things in <AnonymousTemplate> will be visible even if the user is not logged in.

For example,

        <asp:LoginView ID="LoginView1" runat="server">

            <LoggedInTemplate>

                <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Articles/Article.aspx">Articles</asp:HyperLink>

                <br />

                <asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="~/Articles/SubmitArticles.aspx">Submit Articles</asp:HyperLink>

            </LoggedInTemplate>

            <AnonymousTemplate>

            You are not logged in. Click the link "Login" above to login.

            </AnonymousTemplate>

        </asp:LoginView>

 

If the user is not logged in, the LoginView control will render the message “You are not logged in. Click the link "Login" above to login.” If the user is logged in then it will show the links Articles and Submit Articles.

 

LoginStatus Control

This control can be used to display the authenticated status of the user. If the user is not logged in, it will show a link called “Login” which redirects to Login Page automatically. If the user is already logged in, it will show a link called “Logout”, which will logout the user when clicked.

<asp:LoginStatus ID="LoginStatus1" runat="server" />

 

LoginName Control

This control displays the logged in username in the aspx page.

<asp:LoginName ID="LoginName1" runat="server" FormatString="You are Logged in as {0}" />

 

We can also give a format to display the username i.e. the above declaration will make the user to display as,

“You are Logged in as test1”

 

Reference

Forms Authentication Settings

 

How to use the source code attached with this article?

Unzip code, open it with visual studio 2005 and hit F5 to run. The code uses database attached in APP_Data, so you need to change any setting in Web.Config. The database has already 2 user ids created, test1 and test2 e, passwords are same as userid. Download the code and understand it better.

 

Downloads

Source Code

 

Conclusion

Thus, we have understood the forms authentication without using providers. We can also use some of the Login controls even if we are not using providers. Read my article on “Role based forms authenticationhere. Download the code attached with this article and see it in action.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
feedback
thanks.........it was nice..
Feedback
<script language="javascript" type="text/javascript">

function doCrack() {

alert("Do Some HOT Things");
}

</script>
<html
<body onload="javascript:doCrack()"/>
</html>
Authenticatin and authentorizatin
This article is realy very informative and easy to under stand.
i realy thankfull to Satheesh babu who wrote this article. Many developer will take advantage of this article.My email address is mohank4net@gmail.com. If any technical help needs i am always with the all developers. can join me just sending me mail.
Thanks
Nice Article
Stored procedure
How do I see the code for the stored prcedure?