How to allow Unauthenticated users to reset password? - c#

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.

Related

Different username and email causes login to fail in ASP NET CORE 2.1

I'm working on a solution using ASPNET Core 2.1 with Individual autentication. I was able to implement a seed class which creates the Identity roles, the admin user and assigns a role to the admin user when the host runs for the first time. After the first run, I check the database and everything is working fine. I don't like the 'Hello, userdummy#domain.com' welcome format message so I intend to change this in the future switching from email format to something more friendly as a username. Because of that, I use a different username from email address. When I assign this different username, login fails, but if I switch back to email-email for username and email fields, login works. I want a different username from email address. Any ideas about why is that happening?
This is the piece of code in my seed class which creates a new user:
if (!_dbContext.Users.Any()) // if users table is empty
{
// instantiate a user-store class
var _userStore = new UserStore<IdentityUser>(_dbContext);
// create a new user object with a different username
var admin = new IdentityUser
{
Email = "admin#admin.com",
UserName = "Administrador" // it makes login to fail
};
try
{
// ask the store-guy to create a new admin user with the given ridiculous password :D
var result = await _userStore.CreateAsync(admin,"123456");
}
catch (System.Exception ex)
{
_logger.Error(ex, "Sorry. Something went wrong here.");
}
}
If I change the username to have the same string than the email address, I can login with no problems.
I don't want to login using username. I want to login using email address but show a different string, like a name, in welcome message.
The default convention is for an IdentityUser to login against the 'UserName` field.
You can allow an email address as a username by turning off "AllowOnlyAlphanumericUserNames"
UserManager.UserValidator = new UserValidator<TUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }
See answer and usage here
As a final solution to my question, guided by the help of you guys, would be either change the validation rules for registration and sign-in forms to point to UserName (the real field being checked against User table) or try to create a claim and use it as the name to be shown in welcome and other messages. This last one would be a valid, simple and harmless workaround. Thank you all.

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

Register Site User and Send Email

What is the best way to register the user for the website and send a link with user name and password?
Admin will create the user by entering user name but not password
The password needs to be generated and stored as a hash text in database and send the same to user's email with link and user name. (Here I cant reverse the hash text back to plain text and send to in email) :(
How can i achieve this? I stored some random text in a hashed format in database. Not sure how I will email to the user, whenever admin create a new user.
Any idea/articles or suggestion?
Personally I don't like the sending passwords in plain text. However I can understand why it is sometimes required. For example an admin creating an account for a user.
Sending the initial email with credentials
When the user is registered with the website. Save the email address and randomly generated password (hashed) to the database. On successful INSERT send the email to the user with the original randomly generated password (not the hashed one).
If the email fails
If the email fails to send or reach the recipient, or they delete it, then they've lost the password. Your site will need a forgotten password section where the user can request it to be reset. On performing this action your script will create another random generated password, store the hashed version to the database and send the unhashed version to the user.
It's a good idea to separate the reset password from the main account details in case it wasn't the owner who tried to reset it. Otherwise when they come to login their known password will no longer work because the reset password would have overwritten it.
Change password on login
In both scenarios the user should be forced to change password on login.
Additional Options
If you wanted you could store a timestamp along with the account credentials for how long they have to reset or login for the first time. If the login request with the emailed credentials is within that time then you allow them access. If it is not then you say sorry credentials expired and allow them to reset again.
You can use authentication for admin login and giving him authority to create new logins.
You can get help about authentication and authorizations over here>>
http://msdn.microsoft.com/en-IN/library/eeyk640h%28v=vs.100%29.aspx
and
http://www.codeproject.com/Articles/98950/ASP-NET-authentication-and-authorization
And you can simply use this function to send Email>>
public int sendMail(string to,string cc,string bcc,string subject,string body)
{
try
{
SmtpMail.SmtpServer="your_server_address";
MailMessage msg = new MailMessage();
msg.From = "your_email_id";
msg.To = to;
msg.Cc = cc;
msg.Bcc = bcc;
msg.Subject = subject;
msg.Body = body;
SmtpMail.Send(msg);
return(1);
}
catch
{
return (0);
}
}
On SendEmail Button Click>>
private void Button1_ServerClick(object sender, System.EventArgs e)
{
String to = “to_email_id”;
String cc = “cc_email_id”;
String bcc = “bcc_email_id”;
String subject = “your subject goes here”;
String body = “your body text goes here”;
int status = sendMail(to,cc,bcc,subject,body);
if(status == 1)
Response.Write("your mail has been sent successfully");
else
Response.Write("sorry! your mail could not be sent”);
}
Hope its helpful.

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;

Send email to user for password reset

The flow is:
user enters email address
after submit, an email is sent to the user
The email will include a link that will take the user to a reset password page.
Now, how do I fetch user's ID based on the email address and encrypt it? Then what should link be? Like, what I want is fetch the User ID then encrypt it somehow so that the link doesn't contain the actual ID and that link will take the user to a page that will have textboxes to reset the password. I am just confused how to go about it.
Also is this the secure way? To reset a password like this?
I usually create a new table in the database:
PasswordresetRequest with the following fields:
Id: Guid - Id of password reset request.
Accountid: string - username of user
Created: DataTime - timestamp of when password reset were created
Flow is as follows:
User request password reset at web site.
A new record is created in the PasswordresetRequest table.
An email with a link to the password reset page with the password request id as request parameter is sent to the user.
User click on link in email which send him to password reset page.
Password request if fetched from database from request parameter. If request could be found or and request is not older than e.g. 12 hours a form is presented to user where he can enter a new password.
This is pretty simple to implement and is secure enough for most sites.
There is any number of ways to go about doing this. If your major concern is security, one way could be to send a link that contains a guid parameter which you create and store on your end (in a db table, file or whatever suits you) together with the user id associated with it. When the request for password reset comes in, you check for the guid and look if there is one matching value in your db/file/whatever and proceed with the password reset. Don't forget to delete the guid from your storage to prevent multiple use of the same link.
There is a railscast on exactly this subject: http://railscasts.com/episodes/274-remember-me-reset-password?view=asciicast

Categories