.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Forum >> C# >> Post New QuestionBookmark and Share Subscribe to Forum

How to validate username and passsword from database using ASP.net C# Sqlserver-2005

Posted By: mohan     Posted Date: November 21, 2010    Points:2   Category :C#
i am creating website it has login form when user come visit the website he/she may upload the profile details or company profile details. when user login it must check the database whether the user registered or not .it mean it check the username and password. so give me c# code with sql server db. using store procedure or without store procedure

thanks alot

Responses
Author: Sadhuryan             
Posted Date: November 22, 2010     Points: 5   

Mohan,

Create an ASP.NET Application Using C# .NET

1. Open Visual Studio .NET.
2. Create a new ASP.NET Web application, and specify the name and location.


Configure the Security Settings in the Web.config File
This section demonstrates how to add and modify the <authentication> and <authorization> configuration sections to configure the ASP.NET application to use forms-based authentication.


1. In Solution Explorer, open the Web.config file.
2. Change the authentication mode to Forms.
3. Insert the <Forms> tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation or the QuickStart documentation that is listed in the REFERENCES section.) Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the <authentication> section of the file:

<authentication mode="Forms">
<forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx"
protection="All" path="/" timeout="30" />
</authentication>



4. Deny access to the anonymous user in the <authorization> section as follows:

 <authorization>
<deny users ="?" />
<allow users = "*" />
</authorization>




Create a Sample Database Table to Store Users Details
This section demonstrates how to create a sample database to store the user name, password, and role for the users. You need the role column if you want to store user roles in the database and implement role-based security.


1. On the Start menu, click Run, and then type notepad to open Notepad.
2. Highlight the following SQL script code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu to paste the following code:

 if exists (select * from sysobjects where id = 
object_id(N'[dbo].[Users]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
[uname] [varchar] (15) NOT NULL ,
[Pwd] [varchar] (25) NOT NULL ,
[userRole] [varchar] (25) NOT NULL ,
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH NOCHECK ADD
CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED
(
[uname]
) ON [PRIMARY]
GO

INSERT INTO Users values('user1','user1','Manager')
INSERT INTO Users values('user2','user2','Admin')
INSERT INTO Users values('user3','user3','User')
GO



3. Save the file as Users.sql.

4. On the Microsoft SQL Server computer, open Users.sql in Query Analyzer. From the list of databases, click pubs, and run the script. This creates a sample users table and populates the table in the Pubs database to be used with this sample application.


Create a Logon.aspx Page

1. Add a new Web Form to the project named Logon.aspx.
2. Open the Logon.aspx page in the editor, and switch to HTML view.
3. Copy the following code, and use the Paste as HTML option on the Edit menu to insert the code between the <form> tags:

  <h3>
<font face="Verdana">Logon Page</font>
</h3>
<table>
<tr>
<td>Email:</td>
<td><input id="txtUserName" type="text" runat="server"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserName" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input id="txtUserPass" type="password" runat="server"></td>
<td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserPass" />
</td>
</tr>
<tr>
<td>Persistent Cookie:</td>
<td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>
<td></td>
</tr>
</table>
<input type="submit" Value="Logon" runat="server" ID="cmdLogin"><p></p>
<asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />



This Web Form is used to present a logon form to users so that they can provide their user name and password to log on to the application.

4. Switch to Design view, and save the page.


Code the Event Handler So That It Validates the User Credentials
This section presents the code that is placed in the code-behind page (Logon.aspx.cs).


1. Double-click Logon to open the Logon.aspx.cs file.
2. Import the required namespaces in the code-behind file:

using System.Data.SqlClient;
using System.Web.Security;



3. Create a ValidateUser function to validate the user credentials by looking in the database. (Make sure that you change the Connection string to point to your database ).

 private bool ValidateUser( string userName, string passWord )
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;

// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ( ( null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );
return false;
}

// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ( ( null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )
{
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );
return false;
}

try
{
// Consult with your SQL Server administrator for an appropriate connection
// string to use to connect to your local SQL Server.
conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );
conn.Open();

// Create SqlCommand to select pwd field from users table given supplied userName.
cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );
cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );
cmd.Parameters["@userName"].Value = userName;

// Execute command and fetch pwd field into lookupPassword string.
lookupPassword = (string) cmd.ExecuteScalar();

// Cleanup command and connection objects.
cmd.Dispose();
conn.Dispose();
}
catch ( Exception ex )
{
// Add error handling here for debugging.
// This error message should not be sent back to the caller.
System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );
}

// If no password found, return false.
if ( null == lookupPassword )
{
// You could write failed login attempts here to event log for additional security.
return false;
}

// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return ( 0 == string.Compare( lookupPassword, passWord, false ) );

}



4. You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.

* Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:

private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,
chkPersistCookie.Checked);
else
Response.Redirect("logon.aspx", true);
}



* Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.

private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect==null)
strRedirect = "default.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}



5. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:

this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick); 



Create a Default.aspx Page
This section creates a test page to which users are redirected after they authenticate. If users browse to this page without first logging on to the application, they are redirected to the logon page.

1. Rename the existing WebForm1.aspx page as Default.aspx, and open it in the editor.
2. Switch to HTML view, and copy the following code between the <form> tags:

 <input type="submit" Value="SignOut" runat="server" id="cmdSignOut">



This button is used to log off the forms authentication session.
3. Switch to Design view, and save the page.
4. Import the required namespaces in the code-behind file:

using System.Web.Security;


5. Double-click SignOut to open the code-behind page (Default.aspx.cs), and copy the following code in the cmdSignOut_ServerClick event handler:

  private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("logon.aspx", true);
}



6. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:

this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);


7. Save and compile the project. You can now use the application.


Hope, this will help you.

Author: Naresh             
Posted Date: November 22, 2010     Points: 5   

Hi Mohan,

Here is a code to check whether user is present ar not , if present redirect to next page else it will throw error message. Hope this code wil l be useful to u.

SqlConnection con= new SqlConnection("Server=LocalHost;DataBase=Test;Uid=sa;Pwd=sa");
string sql;
sql = "select * from login where username ='" + this.TextBox1.Text.Trim() + "' and password= '" + this.TextBox2.Text.Trim() + "' ";
SqlCommand cmd1 = new SqlCommand(sql, con);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
Response.Redirect("NextPage.aspx");
}
else
{
MessageBox.Show("invalid username and password");
}


Thanks
Naresh

Thanks
Naresh
Author: krishana singh             
Posted Date: November 30, 2010     Points: 5   

if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand("select name,password from tbllogin where name='" + txtusername.Text + "' and password='" + txtpassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
this.Hide();
Form1 fm = new Form1();
fm.Show();
}
else
{
MessageBox.Show("Incorrect UserName and Password", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();

Author: krishana singh             
Posted Date: November 30, 2010     Points: 5   

in web development......


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class login : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionstring"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
txtmailid.Text = Request.QueryString["mailid"].ToString();


}
catch (Exception ex)
{

}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
con.Open();
string query = "select count(*) from login where email='"+txtmailid.Text+"' and password='" +txtpassword.Text+ "'";
SqlCommand cmd = new SqlCommand(query, con);
if (con.State == ConnectionState.Closed)
con.Open();
int v = Convert.ToInt32(cmd.ExecuteScalar());
if (v != 0)
{
Session["UserID"] = txtmailid.Text;
Label lbm = new Label();
lbm.Text = Session["UserID"].ToString();
Response.Redirect("profile.aspx");
con.Close();

}


else
{
lblMessage.Visible = true;
lblMessage.Text = "Invalid EmailID or Password";
}
}
}


Author: krishana singh             
Posted Date: November 30, 2010     Points: 5   

if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand("select name,password from tbllogin where name='" + txtusername.Text + "' and password='" + txtpassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
this.Hide();
Form1 fm = new Form1();
fm.Show();
}
else
{
MessageBox.Show("Incorrect UserName and Password", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
con.Close();



Post Reply

You must Sign In To post reply
 
 
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery
JavaScript/VBScriptBiztalkWPFPatten/PracticesWCFOthers
www.DotNetSpark.comUnAnsweredAll

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend