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)
Related
I am trying to download a file that is behind a login page. I have looked into many ways to add credentials but the response is always the log in page's html. I have tried 2 passes with client.uploadValues or client.uploadstring to get a cookie and a single pass just providing credentials.
Public Sub downloadImage()
Dim username As String = "xxxxx"
Dim password As String = "xxxxx"
Using client As New WebClient()
client.Credentials = New NetworkCredential(username, password)
client.DownloadFile("https://retailerservices.domain.com/Image/ItemHighRes/26634/1", AppDomain.CurrentDomain.BaseDirectory & "test.jpg")
End Using
End Sub
Any recommendations?
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()
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.
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...
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