Confirm Delete with Password in ASP.NET MVC - c#

I have a need to have my users enter their passwords when confirming a delete action. However I do not know how to compare their input to their passwords.
My algorithm is something like:
read passwordFieldText
if userpassword == passwordFieldText
{
execute delete action
}
else return "incorrect password"
I know of course that there is no way to retrieve a user's password as a variable, so how do I go about achieving this?

You don't compare their input to their password yourself. You pass their username and what they are now saying their password is into Membership.ValidateUser.
if (Membership.ValidateUser(username, password))
// Do Delete
else
// Don't do Delete
Documentation can be found at here.

You are going wrong. because if same password have two different user, then delete action is call unrelated :p . It's tooo bad
So you need
read passwordFieldText
if userid=currentuserId && userpassword == passwordFieldText
{
execute delete action
//delete action look like
delete from user where userid=currentuserId and userpassword == passwordFieldText
}
else return "incorrect password"
and how can check your password
see this samples
http://www.codeproject.com/Articles/689801/Understanding-and-Using-Simple-Membership-Provider
http://www.codeproject.com/Articles/664294/ASP-NET-MVC-Configuring-ASP-NET-MVC-4-Membership-w
Update
You can get, how to check the password mach or email mach in membership table by this link
http://www.itorian.com/2013/03/PasswordResetting.html

Related

How to check if entered password is equal to stored password?

Suppose I've implemented a method to change the password in the user panel. Before doing the change, I ask to the user to enter the current password, I actually created this method:
[HttpPost]
[ValidateAntiForgeryToken]
public bool CheckCurrentPassword(string username, string password)
{
var originalUser = _userManager.Users.FirstOrDefault(c => c.UserName == username);
var hash = _userManager.PasswordHasher.HashPassword(originalUser, password);
if (hash == originalUser.PasswordHash)
return true;
return false;
}
essentially I send to this method the username which is an unique field and I can retrieve the user which asked for password change. I get also the hash of the new password and then compare the hash to the stored hash in the database.
The problem is that the hash is different. I don't know why but with the same password I have two different hashes (one stored in the db) and another generated on the fly by the method.
Maybe there is another way to check if the current password is equal to the entered password?
This is exactly what UserManager<TUser>.CheckPasswordAsync(TUser, String) is for:
if (await _userManager.CheckPasswordAsync(originalUser, password))
{
// Yes, it's the current password.
}
While you're at it, you're better off using UserManager.FindByNameAsync(String) to get your originalUser. The entire function could become:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<bool> CheckCurrentPassword(string username, string password)
{
var originalUser = await _userManager.FindByNameAsync(username);
// originalUser might be null (as in your example), so check for that accordingly.
return await _userManager.CheckPasswordAsync(originalUser, password);
}
Using the Async methods requires your calling code to use async/await, which I've folded into the example above. Actions support this out of the box; handling a return type of Task<T>.
If you're interested in how the CheckPasswordAsync function is implemented, you can see for yourself in the source code, which might help you determine why your own version isn't working.
If the hashes are different then the method used to hash the password before entering it into the database must be different from_userManager.PasswordHasher.HashPassword. Can't really think of any other explanation. See if you are able to match the two ways of hashing.
I also encountered this problem, it was caused because the Hashing that was being made in the MVC project got manipulated by the SQL Database in some way, so this way (below) is how I managed to work around the issue of having a miss match in hashed password when comparing entered password and comparing to existing password in SQL Database.
You could try a slightly different way of comparing the entered password with the existing password.
public ActionResult Login(UserLogin login)
{
var v = dc.Users.Where(a => a.UserEmailAddress == login.UserEmailAddress).FirstOrDefault();
if(string.Compare(Crypto.Hash(login.UserPassword), v.UserPassword) == 0)
{
//do login here
}
}
So if you have your controller set up to accept the login details from the form, you will be able to use the "login" to find the User in the database that you are trying to log in. With this User being found in the query, u can then proceed to perform the "string.Compare"
I hope this helps.

Reset Password e- mail... recent email should work , not previous

Reset Password Email - If two reset Password email has been sent , then the recent one should only work. Previous one should n't redirect to a reset password page.. Provide me a hint what can i do to make it work as required
Add a VerificationCode-column to the database where the passwords are saved
Username Password VerificationCode
user1 Pass1 dfsdb-dfb-anda
Password reset link will consist of a randomly generated verificationCode (as a query parameter).
/account/ResetPassword?user=user1&VerificationCode=dfsdb-dfb-anda
On receiving a request from reset form, to change password, verify the username and verificationCode combination. Once the user has changed the password, delete the verification code from the database.

MVC4 Pattern for receiving password reset token

Trying to get password reset functionality in place. This will be for a user who has not and cannot log in to the system. I think I'm close but it doesn't feel right:
I have a ResetPassword method/view...it simply asks for the user's email address, does not confirm an account to the user but if one exists, sends email with link+token. That all works fine.
The next part is where my questions are....I receive the password token with this method (via the user's email link being clicked):
[HttpGet]
public ActionResult ReceiveResetToken(string token)
{
try
{
if (!String.IsNullOrEmpty(token))
{
var username = (from u in db.Users
where u.Userid == WebSecurity.GetUserIdFromPasswordResetToken(token)
select u.Email).ToString();
if (!String.IsNullOrEmpty(username))
{
WebSecurity.ConfirmAccount(token);
}
}
RedirectToAction("Index", "Home");
}
catch (Exception)
{
throw;
}
}
I'm missing something obvious here. The method isn't complete because I keep rethinking it...get the username, confirm the account, somehow log them in without knowing what their password is, redirect to change password page? Doesn't feel right.
So then I thought maybe pass along the hidden username with a ViewBag to the change dialogue...doesn't feel right either. I'd like a more elegant approach, receive the token, ask the username for the new password, update db and login. What is the pattern for receiving a password reset token?
EDIT -------
So as I am continuing to search for answers, I came across this little gem. Apparently there is a WebSecurity.ResetPassword method that accepts the token and a new password. This feels like the right path, no need to worry about logins, just change it and redirect to login...I'll finish up the code and post a solution as this seems to be a popular and often unanswered question on SO.
If anyone could confirm that I'm on the right path or post any thoughts on adding elegance to the pattern that'd be cool
It's a right path !
for me,
User give his email and i send him a token who is generate an GUID and i have passwordResetTokenDate who take a date when user asked the reset. (token is valid 48hours)
in email, there is a link with token and i give him a token, if when he click and something is wrong, he can copy pasted the token in textbox or re-clicking on the link
when he click on the link, i check the token and the date and passwordResetTokenDate if all is right, there is two textbox and user enter 2 times his new password.
when he save his password, i logged him.
WebSecurity.ResetPassword do the job !
here an example : (i have a custom websecurity with custom provider)
[AllowAnonymous]
public ActionResult ForgotMyPassword(string confirmation, string username)
{
username = HttpUtility.UrlDecode(username);
ViewBag.Succeed = false;
SetPasswordViewModel Fmp = new SetPasswordViewModel(username,confirmation);
return View(Fmp);
}
//
// POST: /Account/ForgotMyPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ForgotMyPassword(SetPasswordViewModel model)
{
ViewBag.Succeed = false;
if (ModelState.isValid)
{
ViewBag.Succeed = WebSecurity.ResetPassword(model.UserName, model.PasswordResetToken, model.Password.NewPassword);
}
if (!ViewBag.Succeed)
{
ModelState.AddModelError("","something"); //something
}
return View(model);
}
This is how it should work (as implemented in ASP Security Kit)
User clicks on forgot password link (which opens /account/forgot for example)
On this page, you ask user for his userName (which could be his email).
You check whether that user exists. If yes, you generate a reset token, saving it in the database for that username and send out an email to that user with a link (http://yourdomain.com/account/confirm/[tokenHere])
You display user a message something like "if you have an account with this username, you will receive an email with instructions to reset your password shortly." but you don't login user on this page because you just asked him for his username!
User receives the email, clicks on the link and the reset password page opens (/account/confirm/[tokenHere])
On this page, user needs to fill password and confirm password fields. Once done you will redirect user to login page (you may argue that you can directly sign in user once he resets his password; but redirecting to login seems to be the standard practice followed on most sites.)
Answering my own question in case it helps anyone.
Provide a form asking for email address to send password reset link
Use WebSecurity.GeneratePasswordResetToken(email, 1440) to generate token
Send email to user with link pointing to a token receiving method
Write an HttpGet method to receive the token and display newPassword form
The form posts the token and the new password model to a method that uses WebSecurity.ResetPassword(token, newPassword)
redirect to login
Haven't written it all out yet but I think this is the way to do it properly

How to allow Unauthenticated users to reset password?

Please see Update Below:
I am using ASP.NET SQL Membership Provider.
So far I am able to allow users to change their password but only if they are authenticated or logged into the application.
What I really need is for users to be able to get a link in an email. They can click this link and reset their password.
Example: Lets say a user forgets his or her password, they can visit a page which they can either enter security question and answer; or their email address on file. They will then get an email with a link to reset their password.
All I have so far is this: Which allows only authenticated users to reset their passwords:
I do not want to use the Recovery Control which generates a password.
public void ChangePassword_OnClick(object sender, EventArgs args)
{
MembershipUser user = Membership.GetUser(User.Identity.IsAuthenticated);
try
{
if (user.ChangePassword(OldPasswordTextbox.Text, PasswordTextbox.Text))
{
Msg.Text = "Password changed.";
}
else
{
Msg.Text = "Password change failed. Please re-enter your values and try again.";
}
}
catch (Exception e)
{
Msg.Text = "An exception occurred: " + Server.HtmlEncode(e.Message) + ".
try again.";
}
}
I can create the store procedure and the email using a String Builder but I do not know how to get the un-authenticated user to change password. Is there a way for the user to be Authenticated when they click the link. I am not sure how to even ask this.
Thanks for reading:
Update:
Okay I managed to get the password to Reset using this code:
protected void btnResetPassword_Click(object sender, EventArgs e)
{
string username = "ApplePie12";
MembershipUser currentUser = Membership.GetUser(username);
currentUser.ChangePassword(currentUser.ResetPassword(), txtResetPassword.Text);
}
Here is my plan:
Make this page public so that it is access by Un-Authenticated Users but only via email link.
Create a Stored Procedure that verifies a user Exists either by the UserName they enter or by the Security Question/Answer.
If they exists, they are sent a link containing a token/GUID
Lastly when they click the link they will land on this page asking them to change password. *The Link Expires as soon as it is used.
My only question is: Doing all of the above requires turning off using security Question/Answer in the Web Config file.
I really would love to have the Security question as an option for the user to either verify by email or security question. If this is not possible, I'll have to create some kind of account number or userid (not membership user id) as an alternative.
My answer is not specific to Membership Provider, but hopefully will point you in the right direction. Typically the way to approach this is to generate a very long random string, called a token. You send them a link that includes this token as a parameter, something like:
http://foo.bar/reset?token=asldkfj209jfpkjsaofiu029j3rjs-09djf09j1pjkfjsodifu091jkjslkhfao
Inside your application you keep track of tokens you have generated. If you receive a request containing that token, you authenticate it as if it was that user.
A couple notes:
The token generated should be random and effectively unguessable in a short period of time.
The token should only work for a short period of time after being generated, ideally shorter than the time required to guess it.
The token should only be usable once. Once a user has changed their password using it, remove it from the system.
Chris has given definitely the correct solution.
You can use the sql table for token management. the token may be UserId or Email that are unique. the link used for reset email like http://test.com/reset?id=sfksdfh-24204_23h7823.
The id in the url is encrypted Userid or Email as you like.
Fetch the detail from table on the basis of id in Url. if id contain in database. then reset the password for user. and remove that token from DB.

WebMatrix.WebData.WebSecurity - How can I get UserName by only having PasswordResetToken

I just wanted to ask for help to get my scenario work? I want to get the UserName using a PasswordResetToken.
This is my scenario.
I have a forgot password feature in my website that would send a passwordresettoken email a change password to the user.
I wanted to send just the passwordresettoken string only.
When the user clicks the link. I will just query the request["token"] to get the username and and then will allow the user to change password and autologin.
this is my code below:
public ActionResult ChangePassword()
{
ChangePasswordModel model = new ChangePasswordModel();
string token=string.Empty;
try
{
token = Request["token"].ToString();
int userId = WebSecurity.GetUserIdFromPasswordResetToken(token);
if (userId > 0)
{
//Get the user object by (userid)
//???????????????????
//???????????????????
}
else
{
throw new Exception("The change password token has expired. Please go to login page and click forgot password again.");
}
}
catch
{
model.HasError = true;
ModelState.AddModelError("", "The change password token has expired. Please go to login page and click forgot password again.");
}
return View(model);
}
Thank you in advance.
Look at the remark at the end of this article: WebSecurity.GeneratePasswordResetToken Method.
I'll copy the relevant part for your convenience:
If users have forgotten their password, they can request a new one. To
provide a new password, do the following:
Create a password-reset page that has a field where users can enter their email address.
When a user has entered his or her email address in the password-reset page, verify that the email address represents a valid
user. If it does, generate a password reset token by calling the
GeneratePasswordResetToken(String, Int32) method.
Create a hyperlink that points to a confirmation page in your site and that includes the token as a query-string parameter in the link's
URL.
Send the link to a user in an email message. When the user receives the email message, he or she can click the link to invoke the
confirmation page.
Create a confirmation page that extracts the token from the URL parameter and that lets the user enter a new password.
When the user submits the new password, call the ResetPassword(String, String) method and pass the password reset token
and the new password. If the token is valid, the password will be
reset. If the token is not valid (for example, it has expired),
display an error message.
Highlighting is mine. Basically you do not need the user name. The framework does all the heavy lifting for you.
Addressing your comment, I would not recommend automatically logging the user in. It's a good practice for them to log manually to check that this password changing thingie has actually worked, and not to discover that it did not only next time around.
Anyway, you can do this:
SimpleMembershipProvider provider = (SimpleMembershipProvider)Membership.Provider;
string username = provider.GetUserNameFromId(userId);
Reference: GetUserNameFromId.
I think the WebSecurity.GetUserIdFromPasswordResetToken(string token) method do what you want.
More info here.
Update:
Sorry but I didn't saw that you were already using that method... So if you want get the username and you are using code first migrations of Entity Framework, you can get the username with the following LINQ expression:
string username = yourDbContext.UserProfiles.FirstOrDefault(up=>up.UserId == userId).Username;

Categories