UserName and UserPassword Verification function - asp.net

i'm afraid to use User forms data to query the database for user login, since the company has only 20 employees, I'm thinking of this function but I'm no sure if this still a easy code to crack for any no so good hacker user
Private Function VerifyCredentials(ByVal User As String, ByVal Password As String) As Boolean
Dim verification As Boolean = False
Dim _conString As String = WebConfigurationManager.ConnectionStrings
("YounnectionString").ConnectionString
'Initialize connections variables
Dim cnn As New SqlConnection(_conString)
Dim cmd As New SqlCommand
cmd.Connection = cnn
cnn.Open()
'No data from the form are used on the SQL Server
cmd.CommandText = "Select UserName, UserPassword from tblUsers;"
Dim cmdReader As SqlDataReader = cmd.ExecuteReader()
'compare the data from the server with the data from the form, it so not matter what the user send from the form
While cmdReader.Read()
If Trim(User) = Trim(cmdReader("UserName"))
AndAlso Trim(Password) = Trim(cmdReader("UserPassword")) Then
verification = True
End If
End While
' this method may result on performance problems if your tblUsers is too big,
'afther all it is the entrance and most of the companies
'just has several hundred users
cmdReader.Close()
cmd.CommandText = ""
cnn.Close()
Return verification
End Function
Please some one check this code and give me better solution, this company was hack ones and the developer was fired. I'm dont know about security but they want a solution while hire a expert. thanks

You are just storing plain text password. Once your database is compromised, you do not have time to notify users.
You need to store hashed password with salt. Although, it can still be cracked (it takes times) but you still have sometime to notify users to change the password.
For ASP.Net, the easiest way will be to use
ASP.NET Universal Providers or
ASP.NET Identity

Let the database filter for you.
Change the query to
"Select UserName, UserPassword from tblUsers
WHERE UserName = " & Trim(User) & " AND UserPassword = " & Trim(Password)
And then, if there is some result the authentication is correct, and if there's no result, obviusly you have to return false, so simply do
Return cmdReader.Read()

Use it
Introducing ASP.NET Identity – A membership system for ASP.NET applications
http://blogs.msdn.com/b/webdev/archive/2013/06/27/introducing-asp-net-identity-membership-system-for-asp-net-applications.aspx

Related

ASP.NET Membership provider password in email replace

We use the built in asp.net membership provider to handle users accounts. The default temporary passwords that the provider creates are a little too complex for our users so I've used the below code to generate one that's a little easier to key in so that they can reset their passwords. It's working perfectly to generate the new passwords and the membership provider is using it instead of the complex one.
Here is where my issue is: When the users request a temporary password the application emails it to them. I'm trying to replace the temporary password with the one I'm generating. You can see in the below screenshots that the password I generate appends to the bottom of the email but I can't get the <%Password%> to be replaced with my new one. What am I missing?
Public Sub PasswordRecovery1_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles PasswordRecovery1.SendingMail
Dim User As MembershipUser = Membership.GetUser(PasswordRecovery1.UserName)
Dim msg As String = e.Message.Body
Dim oldpswd As String = User.ResetPassword()
Dim newpass As String = GetPassword()
msg.Replace("<%Password%>", newpass)
msg += "<p>Your new password is: " & newpass & "</p>"
User.ChangePassword(oldpswd, newpass)
e.Message.Body = msg
End Sub
Email Template I'd like to update with newpass
Email that goes to user still has old password and new one at the bottom
Replaced the "<%Password%>" with "<-TemporaryPasswordArea>" in my template, then changed the msg assignment to the following and it's replacing it correctly in the email.
msg = msg.Replace("<-TemporaryPasswordArea>", newpass)

User details stored in separate table ASP.NET Identity

I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...

ASP.net Coding User Roles into Login Page

I've developed a login page, which functions off of a stored procedure. The login part functions well, however, the website will consist of roles that will determine what page the user is directed to once they are logged into the secure section. The columns I’m focusing on in the database / table are:
Guid -0 column
Login_name -9th column
Login_Pwd -10th column
Role_ID -11th column / Contains a value of 1 or a 2
What I’m trying to do is: get the login page to distinguish between the users with a Role_ID of 1 and those that have a Role_ID of 2. But, currently, when I log into the page, I’m directed to the SecurePage.aspx regardless of what Role ID the user has. Could I please get some direction on this?
This is my Stored Procedure:
ALTER PROCEDURE [dbo].[Check_Users]
#Login_name as varchar(100),
#Login_Pwd as varchar(50)
AS
/* SET NOCOUNT ON */
SELECT * FROM SupplierCompany WHERE Login_name=#Login_name AND Login_Pwd=#Login_Pwd
RETURN
This is the code behind my login button:
Try
Dim con As New SqlConnection(GetConnectionString())
con.Open()
Dim cmd As New SqlCommand("Check_Users", con)
cmd.CommandType = CommandType.StoredProcedure
Dim p1 As New SqlParameter("Login_name", username.Text)
Dim p2 As New SqlParameter("Login_Pwd", password.Text)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
Dim rd As SqlDataReader = cmd.ExecuteReader()
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx")
Else
lblinfo.Text = "Invalid username or password."
End If
'check the Role of the usre logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Catch
Finally
End Try
..Any assistance is greatly appreciated.
Inside your If rd.HasRows Then you redirect to the SecurePage, so I'm guessing it doesn't even reach the while. Try removing the Response.Redirect("securepgaes/SecurePage.aspx") inside this if, and adding the while loop there, like this:
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
'Response.Redirect("securepages/SecurePage.aspx") Remove this line
'check the Role of the user logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Else
lblinfo.Text = "Invalid username or password."
End If
Where have you defined the code to redirect the logged in user?
The Login control by default will try and redirect you to a destination page once successful. I would think you should hook in to the OnLoggedIn event and redirect the page before the server has a chance to do it for you.
As an alternative if that doesn't work you could try building your own 'Login Control' - since you are using a stored procedure to validate users anyway, it's not a huge leap to dump a few textboxes on the page and go that way. At least then you don't need to worry about overriding the default behaviour. I believe ASP.NET provides a bunch of SPs you can use which will validate user passwords and such - check it out on the server (they are all like dbo.aspnet_*.

Get Logged/Signed in Username from DefaultConnection Database VB.net 2012 ASP.NET Web Forms Application

I am a bit new to this web application stuff. When I create a new project in Visual Studios 2012 for ASP.NET Web Forms Application, it generates several predefined pages/functions. I actually want to use these functions since it seems to look like it might save me some time.
At this point I noticed how it has a Register.aspx and Login.aspx, which works fine. The Problem is that I have a database in Access 2007 with some tables. I want to know if it is possible to do one of the following and how:
1) keep the DefualtConnection database and query for the currently logged in username, to then use that usename to query my Access Database for the information based on that username.
2) Create my Own Register and Login using the Access Database. I wonder how do I keep track of the logged in user for this case and I also get an error when using the Create User Wizard
Please help, I need this information so that I can continue working on my final project. The Prof has no clue on how to do this, and I have been searching the web for and answer, however it seems like I may not be asking the right questions. Thanks in advance :)
*Edit
•What I mean by logged in user:
Picture https://dl.dropbox.com/u/22962879/Project_4_Registro_Est/Logged%20in%20user%20Project4.png
•DefaulConnection:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Project_4_Registro_Est-20130131171154;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Project_4_Registro_Est-20130131171154.mdf"
providerName="System.Data.SqlClient" />
•My Access Database
myConn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\cast\Documents\test.accdb")
My Solution:
It turns out that i can get the logged in users name by calling User.Identity.Name.
So I did the following:
'//The following code is an example of using the Logged/signed in username to then'
'//Query other Databases based on the user name:'
Dim myConn As System.Data.OleDb.OleDbConnection
Dim cmd As New System.Data.OleDb.OleDbCommand
Dim sqlstring As String
'//Connecting to My Database:'
myConn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\cast\Documents\test.accdb")
'//Query I wish to use to find all data based on User name:'
sqlstring = "Select FirstName, LastName, UserType FROM users WHERE Username = '" + User.Identity.Name + "'"
Try
'//Start by opening the connection'
myConn.Open()
'//I use str for now to store the results'
Dim str As String = ""
'//Set the command by adding the SQL string and Connection:'
cmd = New OleDb.OleDbCommand(sqlstring, myConn)
'//Create variable which contains results from Executed command:'
Dim oledbReader As OleDb.OleDbDataReader = cmd.ExecuteReader
'//Keep reading each row that contains the Queried Results:'
While oledbReader.Read
'//Store result to str. each item is a Column in the order I Queried'
str = str + (oledbReader.Item(0) & " " & oledbReader.Item(1) & " (" & oledbReader.Item(2)).ToString() & ")" + "\n"
End While
'//Show results on page's Label1:'
Label1.Text = str
'//Close everything'
oledbReader.Close()
cmd.Dispose()
myConn.Close()
Catch ex As Exception
'//show error message if could not connect'
MsgBox("Can not open connection! X_X")
End Try
This should be using SimpleMembership. So ask WebMatrix.WebData.WebSecurity.CurrentUserName. Also WebSecurity.IsAuthenticated would be good to look at.

How can I transfer login value to another page?

I am a newbie in using asp.net with code behind of vb.net I just wanna know on how to see the name of the admin on the POS page. it seems that this code doesn't work??
Main.lbl_name.Text = CurName.ToUpper
POS.lbl_cashier.Text = CurName.ToUpper
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd1 As New SqlCommand
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "SELECT * from UserTable WHERE Username ='" & txt_username.Text & "'"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
If txt_username.Text = rdr.Item(0) And txt_password.Text = rdr.Item(3) Then
CurPos = rdr.Item("Type")
CurUser = rdr.Item("Username")
CurName = rdr.Item("EmployeeName")
If rdr.Item(4) = "ADMINISTRATOR" Then
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
'Main.lbl_name.Text = CurName.ToUpper
'POS.lbl_cashier.Text = CurName.ToUpper
cmd1.Connection.Close()
Response.Redirect("ACESCHOOLSUPPLIES.aspx")
'Me.Dispose()
You can't just access other pages, ASP.NET runtime is ignorant about other pages, you have access to your current page only!
You can use the Session variable to store some data temporarily for current user session, the Session object is available on every ASP.NET Page.
Session("adminname") = CurName
On other page where you want to show it you just reload it from Session
Dim NewName = Session("adminname")
Take some hidden field and use session.add("username") and store your username or which ever you want and the n retrieve that from your second page.
Session.Add("Username",Username);
does essentially the same as
Session["Username"] = Username;
As Alaudo suggested, storing variables in Session state is an option.
For the sake of completeness other options you have are:
Cookies
QueryString
Hidden fields (for POST requests)
The logged on user name is something I personally would not store in Session state or pass around using any of the alternate techniques I mention above.
Looking at your code it seems you are trying to authenticate some credentials (user name/password).
I recommend you look at MemebershipProvider in ASP.NET. Are you familiar with this? You can then easily access the logged in user.

Resources