ASP.net Coding User Roles into Login Page - asp.net

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

Related

How do I log a user back in after change of Email/Username? - Asp.net/VB.Net

I found this code on a site which was written for me and works, and I'm trying to use it on a new site. The code checks that a emailAddress doesn't already exist when a user edits their account details, and because the emailAddress is also used as the underlying .NET membership username it needs to change that too. So far I've managed to get it to change the email address in tblAccounts which is done with this call:
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
Then it needs to check if the user changing the email is the logged in user and re-log them back in. This doesn't seem to work as I get this error from the siteMaster when it tries to redirect to the homepage:
System.NullReferenceException: Object reference not set to an instance of an object.
The error is caused in the siteMaster when it tries to check messages for logged in user and it flags up the last line of this as where the error occurs:
If HttpContext.Current.User.Identity.IsAuthenticated Then
hypSettings.visible=true
Dim counter As Integer = messaging.CheckUnreadMessages(Membership.GetUser.ProviderUserKey)
It therefore looks like the email address is being updated where it should, but the site isn't logging the user back in correctly. As I say, it works on the site where I took the code from and there isn't much difference between the sites, but I don't understand memberships and cookies too well so I'm not sure if something needs altering elsewhere?
Here's the code for changing the users email address:
'Check if the Role has been changed
Membership.ApplicationName = "/OCBS"
Dim userID As Guid = Guid.Parse(Request.QueryString("aID"))
Dim usr As MembershipUser = Membership.GetUser(userID, False)
'Now check if the email address has been changed, because the email address is used for the username then the underlying .NET membership username needs changing
If txtEmailAddress.Text <> lblEmailAddress.Text Then
'Email has been changed, update the username for this user
Dim acc As New accounts(Guid.Empty)
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
'Check if the user changing the email is the logged in user and re-log them back in
If User.Identity.Name = lblEmailAddress.Text Then
'FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, False)
Response.Cookies.Clear()
Dim expiryDate As DateTime = DateTime.Now.AddDays(100)
Dim ticket As New FormsAuthenticationTicket(2, txtEmailAddress.Text, DateTime.Now, expiryDate, True, [String].Empty)
Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket)
Dim authenticationCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
authenticationCookie.Expires = ticket.Expiration
Response.Cookies.Add(authenticationCookie)
End If
End If
Oooh, I've managed it.. I added this..
Session.Abandon()
FormsAuthentication.SignOut()
after line: Response.Cookies.Clear()

ASP application using the saved credentials even after the user cleared the username and password textboxes and hits submit

Could anyone please help, I have an asp application that asks for username and password in the login.aspx page and after logging in with the correct credentials, it prompts me whether to save the credentials. I clicked yes and after some time I logged out, then it takes me to the login.aspx page with the (saved) username and password already filled automatically in the boxes(because I saved previously above). Now my problem is that, now I cleared the username and password that are filled automatically in the boxes and hit submit. Then it should ask for username and password, but now actually it is using the old saved username and password and logging into the application !!!!
*To make it more brief and clear, this is the problem :-
"I am able to login even though I have removed the username and password. I logged out. Erased the content of both fields and then clicked 'Submit'. I was able to get into the Application."
Could anyone help please . Thanks in Advance !!!!
Here's my code for the 'Submit' button 'OnClick' Event :-
Protected Sub SignIn(sender As Object, e As EventArgs)
StatusText.Text = String.Empty
Dim Name As String = UserName.Text
Dim Password As String = UserPassword.Text
If IsValid Then
Try
Dim userStore = New UserStore(Of IdentityUser)()
Dim userManager = New UserManager(Of IdentityUser)(userStore)
userManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10)
userManager.MaxFailedAccessAttemptsBeforeLockout = 7
Dim user = userManager.FindByName(Name)
If user IsNot Nothing Then
If userManager.IsLockedOut(user.Id) Then
StatusText.Text = String.Format("Your account is locked. please contact administrator.")
Else
If userManager.CheckPassword(user, Password) Then
userManager.ResetAccessFailedCount(user.Id)
If Not userManager.GetLockoutEnabled(user.Id) Then
userManager.SetLockoutEnabled(user.Id, True)
End If
Dim tkt As FormsAuthenticationTicket
Dim cookiestr As String
Dim ck As HttpCookie
'Add Session to 5 Hours
tkt = New FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(5), RememberMe.Checked, "")
cookiestr = FormsAuthentication.Encrypt(tkt)
ck = New HttpCookie(FormsAuthentication.FormsCookieName, cookiestr)
If RememberMe.Checked Then
ck.Expires = tkt.Expiration
End If
ck.Path = FormsAuthentication.FormsCookiePath
Response.Cookies.Add(ck)
Dim strRedirect As String
strRedirect = Request("ReturnUrl")
If strRedirect Is Nothing Then
strRedirect = "default.aspx"
End If
Response.Cookies.Add(New HttpCookie("adjusterId", New ContextProvider().GetAdjusterId(user.Id)))
Response.RedirectPermanent(strRedirect)
Else
userManager.AccessFailed(user.Id)
If userManager.IsLockedOut(user.Id) Then
StatusText.Text = String.Format("Your account is locked. please contact administrator.")
Else
StatusText.Text = String.Format("Invalid username or password, you have {0} more login attempt(s) left before account is locked out.", (3 - userManager.GetAccessFailedCount(user.Id)))
StatusText.Visible = True
End If
End If
End If
Else
StatusText.Text = String.Format("Invalid username or password.")
StatusText.Visible = True
End If
Catch ex As Exception
StatusText.Text = String.Format("Unable to login, please contact administrator.")
End Try
Else
StatusText.Text = String.Format("Enter username or password.")
End If
End Sub
Likely the authentication cookie is being remembered, after the initial login, and that still exists.
Somehow when you attempt to login with empty fields, it just uses the cookie instead of the empty fields. That would be my guess.
my best guess is that this method is where you will find the culprit code:
userManager.AccessFailed(user.Id)
It could also be a redirect problem. That you simply attempt to redirect the user back to a page on an invalid login, and since the cookie is still set, you are allow to see whatever page you are getting redirected too.
Main problem, your logout function doesn't remove the authentication cookie.
after a lot of banging, I found out a simple change that fulfilled my requirement, I just added the below properties for my 'username' textbox in .aspx as below :-
<asp:TextBox ID="UserName" runat="server" Width="295px" AutoCompleteType="None" EmptyMessage=" "></asp:TextBox>
(added AutoCompleteType and EmptyMessage).
Not sure whether that's the right approach, but that helps !!!! ThankYou.

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.

Issue Querying LDAP DirectoryEntry in ASP.NET

I have users login to my application via Active Directory and then pull from their AD information to garner information about that user like so:
Dim ID as FormsIdentity = DirectCast(User.Identity, FormsIdentity)
Dim ticket as FormsAuthenticationTicket = ID.Ticket
Dim adDirectory as New DirectoryEntry("LDAP://DC=my,DC=domain,DC=com")
Dim adTicketID as String = ticket.Name.Substring(0, 5)
Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
Session("person_name") = adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value
Now, I want to be able to impersonate other users...so that I can "test" the application as them, so I added a textbox and a button to the page and when the button is clicked the text is assigned to a session variable like so:
Session("impersonate_user") = TextBox1.Text
When the page reloads I check to see if Session("impersonate_user") has a value other than "" and then attempt to query Active Directory using this session variable like so:
If CStr(Session("impersonate_user")) <> "" Then
Dim adDirectory as New DirectoryEntry(LDAP://DC=my,DC=domain,DC=com")
Dim adTicketID as String = CStr(Session("impersonate_user"))
Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value
Session("person_name")= adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value
Else
[use the actual ticket.name to get this info.]
End If
But this doesn't work. Instead, it throws an error on the first Session line stating, "DirectoryServicesCOMException was unhandled by user code There is no such object on the server."
Why? I know I'm giving it a valid username! Is something strange happening in the casting of the session? The code is essentially the same between each method except that in one method rather than pulling from ticket.Name I pull from a session variable for the login I'll be looking up with AD.
Maybe the identity your process is running under needs permissions to access the active directory. You could do this by changing the identity your application runs under in the IIS application pool.
What is entered in the textbox?

Resources