How do I trigger a reset password? - asp.net

I work in Microsoft .NET 4.0 environment.
In my application I enable the user to get new automatic password.
So I use in my .cs file the method:
MembershipUser user = Membership.GetUser();
user.ResetPassword();
I want to trigger on reset Password, means: when the password is changed to the automatic
one, an email will be sent to the user's email address with the new password (that is returned from user.ResetPassword()).
I use standard Membership DB tables.
I wrote the following trigger:
CREATE TRIGGER MembershipChangePass ON aspnet_Membership
AFTER UPDATE,DELETE
AS
BEGIN
DECLARE #user uniqueidentifier
DECLARE #email nvarchar(256)
SELECT #user = (SELECT UserId FROM UPDATED)
SELECT #email =(SELECT LoweredEmail FROM aspnet_Membership
WHERE #user=UserId)
EXEC xp_sendmail #email, ???
END
GO
The problem is how do I get the ??? - the new automatic password I created by
the method: user.ResetPassword();
Can I define the TRIGGER to be used only with user.ResetPassword(), and not with other
methods (like: (user.ChangePassword(...))?
Maybe there is another simple way to trigger reset password?
Thank you.

The ResetPassword() method returns the new password which you can grab and send to the user
string newPassword = user.ResetPassword();
string toAddr = "user email here";
string subject = "Password reset notification";
string body = "Your new password is "+newPassword;
//mail.Send(fromAddr, toAddr, subject, body);

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()

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

how to recheck username and emailid in edit profile page using stored procedure?

In asp.net web page got username, password, emailid from login page using session. In edit profile page user want to change username and emailid and it has been updated in sql db. Before going to update first select the particular user record using session, get new username and new emailid check with records except that user record. If no one in that record means allow user to update otherwise show the msg "already exist". How to do this using stored procedure?
Any one pls provide stored procedure coding for this?
Create PROCEDURE [dbo].[uspUpdateUserName]
#newusername varchar(500),
#newPassword varchar(500),
#UserID int,
#Result int output
AS
BEGIN
if exists(Select username from table
where username = #newusername and Password = #Password)
Begin
Print('already exist')
Set #Result = -1
End
else
Begin
Update table
Set username = #newusername,
Password = #Password
where UserID = #UserID
Set #Result = UserID
End
END

ASP.NET Impersonation design

This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!
If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....
http://msdn.microsoft.com/en-us/library/ff647396.aspx

Create User using Membership.CreateUser

I used the following to create new users using SqlMembershipProvider. While trying to create new users using CreateUserWizard, it throws exception 'The username is already in use' even though there is no any user exists and also new row is creating successfully with this username and password in my table.
MembershipUser newUser = Membership.CreateUser(createWizard.UserName, createWizard.Password);
If i hard code the value of username and password no exception occurs.
Can any one tell me the reason why it throws the exception when using CreateWizard?
MembershipCreateStatus status;
var user = Membership.CreateUser(login, password, email, null, null, true, out status);
Try this.
Check in your Membership.dbo database if this user exists.
SELECT *
FROM aspnet_Users
WHERE (UserName = 'YourUserName')

Resources