VB.NET - ASP.NET - Incorrect Username/Password (Validation) - asp.net

Can anyone tell me from the code what's wrong in the code?
The lbl text should show "Incorrect Username/Password" if the Username and Password do not match.
Code:
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
If (String.IsNullOrEmpty(txtLogin.Text)) Or (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
Try
If read.HasRows Then
While read.Read()
If txtLogin.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tUsername As String = read.Item("Username").ToString
Session("Username") = tUsername
Response.Redirect("Default.aspx")
End If
End While
End If
read.Close()
Catch ex As Exception
Response.Write(ex.Message())
lblLoginError.Text = "Incorrect Username/Password."
lblLoginError.Visible = True
Finally
conn.Close()
End Try
End If
End Sub

Instead of the catch write an Else to the if statements

You can try this code. This code is without Try Catch block.
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
If (String.IsNullOrEmpty(txtLogin.Text)) Or (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
If read.HasRows Then
read.Read()
Session("Username") = read.Item("Username").ToString
read.Close()
conn.Close() 'Close connection before Redirecting.
Response.Redirect("Default.aspx")
Else
read.Close()
conn.Close()
lblLoginError.Text = "Incorrect Username/Password."
lblLoginError.Visible = True
End If
End If
End Sub

You don't need to return the username and password from the database as you have them already. You just need to count the matching entries. This greatly simplifies it. Also, as jams showed, it's better to do the test for values in the username and password fields before doing anything to do with the database:
If (String.IsNullOrEmpty(txtLogin.Text)) OrElse (String.IsNullOrEmpty(txtPassword.Text)) Then
lblLoginError.Text = "One or more fields are empty. Please fill in all the fields"
lblLoginError.Visible = True
Else
Dim ok As Integer = 0
Using conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\PetLandia\App_Data\db.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT COUNT(*) FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
conn.Open()
ok = CInt(cmd.ExecuteScalar())
conn.Close()
End Using
If ok = 0 Then
' credentials incorrect
Else
' credentials correct
End If
End If

The way you've written it, "Incorrect Username/Password" will only show if an exception is thrown.
if you want to use the code as you've written it, add an ELSE:
If txtLogin.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tUsername As String = read.Item("Username").ToString
Session("Username") = tUsername
Response.Redirect("Default.aspx")
else
throw new exception("Incorrect Username/Password")
End If

You decided to roll your own security which led to ...
You appear to be storing passwords in plain text which is a huge security hole and potential source of liability.
If read.HasRows will be false if the passed username and password do not exist in the database. I.e., it will not throw an exception, it will simply return no rows.
You did not call Dispose on the disposable objects.
It would be faster to simply call ExecuteScalar with Select Count(*) to see if the result is greater than zero.
Dim authenticationFailed As Boolean = String.IsNullOrEmpty(txtLogin.Text) _
OrElse String.IsNullOrEmpty(txtPassword.Text)
If Not authenticationFailed Then
Dim connString = "Provider=Microsoft.Jet.OLEDB.4.0..."
Using conn = New OleDbConnection(connString)
Const sql As String = "Select Count(*) From [User] Where Username=? and Password=?"
conn.Open()
Using cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#Username", txtLogin.Text)
cmd.Parameters.AddWithValue("#Password", txtPassword.Text)
Try
Dim result = cmd.ExecuteScalar(CommandBehavior.CloseConnection)
Catch generatedExceptionName As SqlException
authenticationFailed = True
End Try
authenticationFailed = authenticationFailed _
OrElse Convert.ToInt32(result) <> 1
If Not authenticationFailed Then
Session("Username") = txtLogin.Text
End If
End Using
conn.Close()
End Using
End If
If authenticationFailed Then
lblLoginError.Text = "Incorrect username and password"
lblLoginError.Visible = True
End If

Related

VB.Net Code not executing when value is not nullorempty

I'm trying to make fb login for my website. So I put condition if user already exist then it will do login & if not then it perform insert user data.
In following code if string is Not Null Or Empty then I am trying to execute code but by putting breakpoint on my statement I see that if string has value then rest code not executing. What could be the reason? Is I am doing something wrong? My first block of code is working fine(users data fetching from facebook). Problem is in second block where I am checking condition.
Private Sub login_Load(sender As Object, e As EventArgs) Handles Me.Load
FaceBookConnect.API_Key = "XXXXXXX"
FaceBookConnect.API_Secret = "XXXXXXX"
If Not IsPostBack Then
If Request.QueryString("error") = "access_denied" Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('User has denied access.')", True)
Return
End If
Dim code As String = Request.QueryString("code")
If Not String.IsNullOrEmpty(code) Then
Dim data As String = FaceBookConnect.Fetch(code, "me")
Dim faceBookUser As FaceBookUser = New JavaScriptSerializer().Deserialize(Of FaceBookUser)(data)
faceBookUser.PictureUrl = String.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id)
pnlFaceBookUser.Visible = True
lblId.Text = faceBookUser.Id
lblUserName.Text = faceBookUser.UserName
lblName.Text = faceBookUser.Name
lblEmail.Text = faceBookUser.Email
ProfileImage.ImageUrl = faceBookUser.PictureUrl
btnLogin.Enabled = False
End If
End If
If IsPostBack Then
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 50000
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Response.Write("User Already Exist")
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Response.Write("User Added")
Catch ex As Exception
Response.Write(ex)
End Try
End If
con.Close()
End If
End If
End Sub
End Class

using facebook login & integrate with website

I am almost about to finish this. I have taken code from aspsnippets. Just added some of my code to check the conditions. There are two buttons One do login from facebook & fetch information which is working Then on second button click it checks whether userid(got from fb) is exist in my db or not? If not then Insert it in db. But at the end of execution I am getting this exception
MySql.Data.MySqlClient.MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first. at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception) at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.CheckState() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at login.Button1_Click(Object sender, EventArgs e) in C:\Users\Suraj\Desktop\fbLoginTest\login.aspx.vb:line 43
UPDATED
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con.Close()
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
str2 = command.ExecuteReader
command.Dispose()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End If
End Sub
You already opened the connection with:
Dim con As New MySqlConnection("Data Source="server";port=3306;Initial Catalog=db;User Id=user;password=password;")
con.Open()
So, remove the con.Open() calls from within your try..catch clauses.

Update command showing successful but not updating the data - what is wrong in my code?

In my code, I get a result showing "data saved" but in my database, nothing is updating - what is wrong in this?
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
Try
Dim usernameuser As String = Session("user").ToString
conn.Open()
Dim STRLINE = "UPDATE CUSTOMER_LIST_TBL SET FIRST_NAME=#FIRST_NAME,LAST_NAME=#LAST_NAME,SIR_NAME=#SIR_NAME Where (PHONE_NO=#PHONE_NO)"
Dim CMD As New SqlCommand(STRLINE, conn)
CMD.Parameters.AddWithValue("#FIRST_NAME", SqlDbType.NVarChar).Value = f_name.Text.ToString()
CMD.Parameters.AddWithValue("#LAST_NAME", SqlDbType.NVarChar).Value = l_name.Text.ToString()
CMD.Parameters.AddWithValue("#SIR_NAME", SqlDbType.NVarChar).Value = sir_name.Text.ToString()
CMD.Parameters.AddWithValue("#PHONE_NO", SqlDbType.NVarChar).Value = usernameuser
CMD.ExecuteNonQuery()
lblmsg.Text = "data saved"""
Catch ex As Exception
lblmsg.Text = Err.Description
End Try
conn.Close()
End Sub

Facebook & Google Login for asp.net website

For my asp.net website I was trying put feature of FB & Google Login. I found tutorial from ASPSNIPPETS. Now in this what I have done is If user click on Facebook Login button then It first authorize the user & get user details in panel. Then I put my code to check whether user already exist in my db or not. If not then it Inserts user & then put login code. My Problem is after executing first line of code it stops executing further so that It is unable to check whether user is logged in or not & so on. I think it may be because of redirect url which stops further codes o execute. How Can I eliminate this problem?
Protected Sub Login(sender As Object, e As EventArgs)
FaceBookConnect.Authorize("user_photos,email", Request.Url.AbsoluteUri.Split("?"c)(0))
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim query As String = "Select ID, email From users where ID=#id"
con.Open()
Dim cmd As New MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd2)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values('" + lblId.Text + "', '" + ProfileImage.ImageUrl.ToString + "', '" + lblName.Text + "')"
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
dr.Close()
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
Dim con2 As New MySqlConnection("connectionstring")
con2.Open()
Dim cmd3 As New MySqlCommand("Select ID, email From users where ID=#id", con2)
cmd3.Parameters.AddWithValue("#id", lblId.Text)
Dim dr2 As MySqlDataReader = cmd3.ExecuteReader()
If dr2.HasRows Then
'Do Login Code here
Try
Dim str As String = "select * from users where ID='" + lblId.Text + "';"
Dim cmd2 As New MySqlCommand(str, con2)
con2.Open()
Dim da As New MySqlDataAdapter(cmd3)
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
Catch ex As Exception
Response.Write(ex)
con2.Close()
End Try
con.Close()
End If
End If
End If
con.Close()
End Sub
First you can optimise your code :
If Not String.IsNullOrEmpty(lblId.Text) Then
Dim str As String = "select * from users where ID=#id"
con.Open()
Dim cmd2 As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#id", lblId.Text)
Dim da As New Common.DataAdapter(cmd2)
Dim ds As New Data.DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
'Do Login Code here
Try
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
welcome.Visible = True
Catch ex As Exception
Response.Write(ex)
End Try
Else
Try
Dim str1 As String = "INSERT INTO users (ID, DP, displayName) values(#id, #img,#name)"
Dim cmd As New MySqlCommand
cmd = New SqlCommand(req, con)
cmd.Parameters.Add(New SqlParameter("#id", lblId.Text))
cmd.Parameters.Add(New SqlParameter("#img", ProfileImage.ImageUrl.ToString))
cmd.Parameters.Add(New SqlParameter("#name", lblName.Text))
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
End Try
'After insertion you don't have to select from database just send the parameters to cookies
Response.Cookies("User_Type").Value = "users"
Response.Cookies("chkusername").Value = lblId.Text
Response.Redirect(Request.Url.AbsoluteUri)
End If
con.Close()
End If

How to Use a parameter within SQL in Vb 2010 (web developer)

I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"

Resources