How can I transfer login value to another page? - asp.net

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.

Related

show user's details from table on aspx when logged in

I posted a similar question previously but quickly deleted it as the question had a number of errors and was not clear for readers.
I am creating a log in for a patient and when logged in (from the log in page login.aspx) I want them to be redirected to a page (in this case user.aspx) when the log in is authenticated and show their details from a table.
So far I can just get a label to provide user logged in correct or user log in incorrect.
I have a patient table as follows - this is all dummy data and made up user/accounts:
This is the code behind file, have I set a session correctly? and how when the user is authenticated can they be redirected to user.aspx with their corresponding details from a table (for instance their user details)
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_Login
Inherits System.Web.UI.Page
Protected Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim patientNo As String
Dim password As String
Dim bAuthethicated As Boolean
patientNo = txtuser.Text
password = txtpassword.Text
bAuthethicated = CheckUser(patientNo, password)
If bAuthethicated Then
lblresult.Text() = "correct"
Else
lblresult.Text() = "Incorrect Student Number and/or Password"
End If
End Sub
Public Function CheckUser(patientNo As String, password As String) As Integer
Dim cmdstring As String = "SELECT * FROM Patient Where Username=#PATIENTNO AND Password=#PASSWORD"
Dim found = 0
Using conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Laura\Final_proj\App_Data\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#PATIENTNO", SqlDbType.NChar).Value = patientNo
cmd.Parameters.Add("#PASSWORD", SqlDbType.NChar).Value = password
conn.Open()
Dim reader = cmd.ExecuteReader()
While reader.Read()
Session("PatientId") = CInt(reader.Item("PatientId"))
found = CInt(reader.Item("PatientId"))
End While
reader.Close()
End Using
Return (found)
End Function
End Class
I hope someone can help. If I can provide any more information or direction on the question please let me know.
Rather than showing the user that they have successfully logged in, just add the following line of code to redirect them to the user.aspx page:
Response.Redirect("user.aspx", True)
On the user page, you need to check if the Session("PatientId") is empty, if so, then redirect back the login page. If it does have a value, ensure it is a number and then use it to load up the patient details with another DB call.
Also another tip, I noticed your passwords are in plain text. I would highly recommend that you one-way hash them using a simple function for additional security. You can then use the same function to hash the password used on the login page to compare against the database value.

Redirecting a user to appropriate page is not redirecting correctly. Any ideas?

I understand that there are several resources on how to redirect a user to a specific page based on his or her access level.
My issue is that my has some flaws preventing it from working correctly.
Your assistance is greatly appreciated.
Here is what we are trying to do.
We have employees with grievances. These employees are provided with a link to access and file their grievances.
Once the employee has filed his/her grievance, then the employee's manager would then log in and will be redirected to a page that shows all employees who have filed grievances so they review their grievances and determine whether or not the employees are approved to meet a board to review their cases and this is where I am stuck.
There are two tables that I didn't design. So, I am trying to make the best of what I am handed.
One table, called Employee has employee username (employeeID) and password (ssn).
The other table called Details has employeeID (related to Employee table) and ManagerID also related to Employee table by EmployeeID
Once a user files his/her grievance and submits it, his/her manager's ID (EmployeeID) is saved to the details table as ManagerID.
The idea is that once a manager logs into the system and his/her ID (ManageID) is present in details table, s/he will be redirected to a page called Decision.aspx.
When I attempted coding it, everyone, including Managers are being redirected to the same page called LetterOfIntent.aspx.
Any ideas what I am doing wrong?
Code is below:
StrSQL = "Select Dept, division, divisionManager, EmployeeName,Employee.EmpID, Email, SSN,Category FROM Employee e,Details d Where e.empID = d.managerID OR e.empID = #empid and SSN=#Password"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New SqlParameter("#enpid", StrUser)
Dim p2 As New SqlParameter("#Password", StrPass)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
While dr.Read()
If dr("empid") <> "" And dr("ssn") <> "" Then
Session("fullname") = dr("empName")
Session("dept") = dr("Dept")
Session("password") = dr("SSN")
Session("Email") = dr("Email")
Session("division") = dr("division")
Session("empid") = dr("empid")
Session("managerID") = dr("managerId")
Session("Cat") = dr("Category")
BValid = True
Else
End If
End While
' This handles all response per validation
If BValid = True Then
If Session("Cat") = "Pending" Then
Response.Redirect("~/pending.aspx")
ElseIf Session("Cat") = "In Progress" Then
Response.Redirect("~/inprogress.aspx")
ElseIf Session("managerID") <> "" And Session("empid") = Session("managerID") Then '***This is a manager, send him/her to Decision page
Response.Redirect("~/Decision.aspx")
Else '***Ok, this is an employee trying to file grievance, send him to LetterofInternt page.
Response.Redirect("~/LetterOfIntent.aspx?myname= " & Session("empid") & "")
End If
'If all else fails, then reject their athentication attempt and let them know.
ElseIf BValid = False Then
lblMsg.ForeColor = Color.Red
lblMsg.Text = "Login failed. "
End If
I suspect that you need to ToString each of the values you're putting into session, like this:
Session("Cat") = dr("Category").ToString()
You'd need to put some null checking around each one but given the information it seems like its probably you're issue.

UserName and UserPassword Verification function

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

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_*.

Evaluating whether a page is the result of a referral from a particular page

I have an Edit Profile page which allows users to change their information - currently it only allows users who have a record in the table 'userprofiles' to edit their information. I want newly registered users to be able to edit their profiles as well.
At the minute, I am using the ASP.NET membership system with the appropriate asp.net_ tables in an Access database to store user credentials. The 'userprofiles' table is a separate table which has more personal information in it. There is no link between the two tables
Here is my code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsCrossPagePostBack Then
SeparateNewUserFunction()
Return
End If
If Not IsPostBack Then
DisplayData()
SaveConfirmation.Visible = False
End If
End Sub
And here is my DisplayData() function just if anyone was interested as to what it does:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim newEmailAddress = ""
Dim newDescription = ""
If Not IsDBNull(profileDr("EmailAddress")) Then newEmailAddress = profileDr.Item("EmailAddress")
If Not IsDBNull(profileDr("Description")) Then newDescription = profileDr.Item("Description")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
description.Text = newDescription
email.Text = newEmailAddress
conn.Close()
End Sub
Rather than checking if a record exists in the 'userprofiles' table that matches the User.Identity.Name of the current user, I thought it would be easier just to evaluate whether or not the user had just been redirected from the Register.aspx page. (If this evaluation is true, then as you can see above, a separate "New User" function will be called).
That is my logic, but I have no clue if VB.NET has a "referrer" or "isReferred" expression? (at the minute as you can see I thought isCrossPagePostback might be the right thing but no luck!)
Any ideas?
You need to check whether or not a record exists and base your logic on that. That is the only right way to do it. As in:
What if you introduce a new page to handle registrations? This logic breaks.
What if you one day you retire and the next guy decides to rename the Register.aspx page? This logic breaks.
What if user hits back button and clicks the Register button again? This logic may break.
You should also consider a foreign key and unique constraint on that table, as well as using UserId instead of TravellerName. TravellerName can change, UserId will not.
... and yes you can the referring page by using HttpRequest.ServerVariables, which gets you a list of IIS Server Variables.

Resources