ARTICLE

Login Control in ASP.NET 3.5

Posted by Raj Kumar Articles | Learn .NET July 28, 2008
In this step by step tutorial, I am going to discuss the Login control available in ASP.NET 3.5.
Reader Level:
Download Files:
 

The ASP.NET login controls provide a robust login solution for ASP.NET Web applications without requiring programming. By default, login controls integrate with ASP.NET membership and forms authentication to help automate user authentication for a Web site. It provides you with a ready-to-use user interface that queries the user name and password from the user and offers a Log In button for login. It validate user credentials against the membership API and encapsulating the basic froms authentication functionality like redirecting back to the original requested page in a restricted area of you application after the successful login.

The Login control displays a user interface for user authentication. The Login control contains text boxes for the user name and password and a check box that allows users to indicate whether they want the server to store their identity using ASP.NET membership and automatically be authenticated the next time they visit the site.

The Login control has properties for customized display, for customized messages, and for links to other pages where users can change their password or recover a forgotten password. The Login control can be used as a standalone control on a main or home page, or you can use it on a dedicated login page. If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.

Note - Login controls might not function correctly if the Method of the ASP.NET Web page is changed from POST (the default) to GET.

Ø  Start Microsoft Visual Studio 2008

Ø  Create a new ASP.NET WebSite, Like this:


Ø 
Drang and drop Login control on page from ToolBox.

 

 

Figure 1.

Whenever user hits the Log In button, the control automatically validates the user name and password using the membership API function Membership.ValidateUse() and then calls FormAuthentication.redirectFromLoginPage() if the validation was successful. All options on the UI of the LoginControl affect the input delivered by the control to these methods. For Example, if you click the "Remember me next time" check box, it passes the value true to the createPresistentCookie parameter of the RedirectFromLoginPage() method. Therefore, the FormAuthenticateModule creates a persistent cookie.

There are three Login Tasks by default.

·         Auto Format - you can select default schemes.

·         Convert To Template - You can edit content of Login Control.

·         Administer Website - You can configure Web Site Administration Tools, Like Security, Application, Provider.

 

Figure 2. 

<form id="form1" runat="server">

<div>

<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

    </div>

    </form>

You can change styles of LoginControl using css too,  Like this:

.LoginControl

{

      background-color:#F7F7DE;

      border-color:#CCCC99;

      border-style:solid;

    border-width:1px;

    font-family:Verdana;

    font-size:10px;    

}

And now apply css to control:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Login Control</title>

    <link href="StyleSheet.css" type="text/css" rel="Stylesheet" />

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Login ID="Login1" runat="server" CssClass="LoginControl">

            <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

        </asp:Login>

    </div>

    </form>

</body>

</html>

 

If you running the page and if the CSS file is placed in a directory where anonymous access is denied, the add the following configuration for the CSS file to you web.config file.

<location path="StyleSheet.css">

<system.web>

<authorization>

<allow users="*"/>

</authorization>

</system.web>

</location>

 

You can add several hyperlinks to your Login control, such as hyperlink to a help text page, or a hyperlink to to a registration page.

 

<asp:Login ID="Login1" runat="server" CssClass="LoginControl"

CreateUserText="Register"

CreateUserUrl="~/Register.aspx"

HelpPageText="Additional Help" HelpPageUrl="~/Help.aspx"

InstructionText="Please enter your user name and password for login.">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

Looks like this :

Here is .CS Code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

            ViewState["LoginErrors"] = 0;

    }

 

   protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

    {

        if (YourValidationFunction(Login1.UserName, Login1.Password))

        {

           // e.Authenticated = true;

            Login1.Visible = false;

            MessageLabel.Text = "Successfully Logged In";

        }

        else

        {

            e.Authenticated = false;

        }

    }

   

  

 protected void Login1_LoginError(object sender, EventArgs e)

    {

        if (ViewState["LoginErrors"] == null)

            ViewState["LoginErrors"] = 0;

 

        int ErrorCount = (int)ViewState["LoginErrors"] + 1;

        ViewState["LoginErrors"] = ErrorCount;

 

        if ((ErrorCount > 3) && (Login1.PasswordRecoveryUrl != string.Empty))

            Response.Redirect(Login1.PasswordRecoveryUrl);

    }

 

 private bool YourValidationFunction(string UserName, string Password)

    {

        bool boolReturnValue = false;       

        string strConnection = "server=.;database=Vendor;uid=sa;pwd=wintellect;";

        SqlConnection sqlConnection = new SqlConnection(strConnection);

        String SQLQuery = "SELECT UserName, Password FROM Login";

        SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);

        SqlDataReader Dr;

        sqlConnection.Open();

        Dr = command.ExecuteReader();

        while (Dr.Read())

        {

            if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))

            {

                boolReturnValue = true;

            }

            Dr.Close();

            return boolReturnValue;

        }

        return boolReturnValue;

    }

}

 

If you insert wrong username and password then message will show like this:

If you insert right usename, password then redirect your page whereever you want or you can show message in ErrorLabel, Like this:

I am attaching my database with application in App_Data folder, if u want use my database then attach my .MDF file.

Any question and queries ask me any time.

Login to add your contents and source code to this article
Article Extensions
Contents added by pandurang pailvan on Apr 15, 2013
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <asp:Login ID="Login1" runat="server" 
                BackColor="#F7F7DE" BorderColor="#CCCC99" 
                BorderStyle="Solid" BorderWidth="1px" 
                Font-Names="Verdana" Font-Size="10pt" CreateUserText="Register" 
            InstructionText="Please enter your user name and password for login." 
            Height="172px" onauthenticate="Login1_Authenticate" 
            onloginerror="Login1_LoginError">
        <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
        </asp:Login>
    </div>
    </form>
</body>
</html>

Contents added by Ganesh on Feb 05, 2010
but how to configure website administration tool and how to strore username and password in login folder of pur database?
post comment
     

I want to develop a site--Online Examination system. For this How can i develop the admin panel??plz explain in detail i am new to asp.net.

Posted by Punita Oct 02, 2012

From Visual Studio, in your Server Explorer tab, you'll notice all of the tables created by default. As well, there are Views, Stored Procedures, etc. First, we want to create a SQL script to recreate all of those objects. So right click the database and select Publish To Provider.This will bring up the Database Publishing Wizard. Select the button to continue.You will be presented with a list of your databases and asked to select your database. There is a checkbox to Script all objects in the database. Select it. Select Next to continue.Now you are given the option to script to a file. It presents a default path, I changed mine.In the next window you will be offered several options. In my case, I needed to change the target database to SQL Server 2008. Select the target you need, then Select to continue. As per Chris Rivera's comment below this blog, if 2008 doesn't show as an option, make sure you download and install SP1.Next you may review the options selected.Click Finish to complete the Wizard. You'll see the progress.Now you have a fancy script generated for you. This script will select, alter, drop, update, insert, etc. etc., all needed values. Now to get this to your database server. Mine happens to be on the same network as my webserver, but not on the same network as my development box, so I created a folder within my project and placed the script in there. When I updated my project, this sql script was then copied to my web server. From my database server, I then copied it via the network to my SQL Server 2008 Web Edition desktop. I opened my Microsoft SQL Server Management Studio and created my new blank database. Just right click Databases, and select New Database. Give it a name and select OK. Then with this new database selected, click the sql file on your desktop and it will open up in your screen. Again, with the new database selected, right click in the script and select "Execute." This will execute the script on the selected database and create all the objects needed.

Posted by Raj Kumar Sep 05, 2011

Hello My dear i have implemented in my local server but still there is a problem with my Login1.PasswordRecoveryUrl not working well while i have typed password wrong more than three times. . . Please revert me back Thanks in advance Yogesh chandra upreti

Posted by Yogesh Upreti Aug 09, 2011

No reconoce a login1 Error 2 El nombre 'Login1' no existe en el contexto actual C:\Users\Emmanuel\Documents\Visual Studio 2010\Projects\WebApplication3\WebApplication3\Default.aspx.cs 36 36 WebApplication3 n

Posted by EMMANUEL JESUS Jul 26, 2011

How to deploy ASPNETDB.mdf to remote server (from local PC to Internet) and what changes that required to be done on web.config file? Thank you - Hassan Shaqhan - ShaqhanHA@yahoo.com

Posted by Hassan Shaqhan Jul 11, 2011
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.