20 secrets of mvc3-(6) retrieve forgotten passwords

Source: Internet
Author: User
Tags lost password

Problem

A user on your website has already registered on your website, but he forgot his password. Now he needs to retrieve it in one way.

Solution

To allow users to retrieve their passwords, a new action and a new view must be added to accountcontroller. This function will use the membership class to find a matching user and send an email containing its password to their related mailbox.

Discussion

By default, MVC Internet applications use one-way hash to encrypt passwords. In this way, the password cannot be retrieved. In the example below. The default encryption method uses bidirectional encryption. This is not very safe. HoweverThis avoids forcing users who forget their passwords to reset their passwords..

First, modify the membership configuration in Web. config.

 <?  XML version = "1.0"  ?> 
< Configuration >
...
< System. Web >
...
< Membership >
< Providers >
< Clear />
< Add Name = "Aspnetsqlmembershipprovider" Type =
"System. Web. Security. sqlmembershipprovider"
Connectionstringname = "Applicationservices"
Enablepasswordretrieval = "True" Enablepasswordreset =
"False" Requiresquestionandanswer = "False"
Requiresuniqueemail = "False" Passwordformat =
"Encrypted" Maxinvalidpasswordattempts = "5"
Minrequiredpasswordlength = "6"
Minrequirednonalphanumericcharacters = "0"
Passwordattemptwindow = "10" Applicationname = "/" />
</ Providers >
</ Membership >
< Machinekey
Validationkey =
"2cf9ff841a23108cfa5d655790d9308656b1f7532c0b95b5c067f80c45e59875
E2f3d68dac63b5024c31d974d4be151341fb8a31fc4bc3705df5398b553fc3c3"
Decryptionkey = "8e71407b62f47cca3aaa6546b3880e1a0ef9833700
E0a0c511710f537e64b8b6" Validation = "Sha1" Decryption = "AES" />
...
</ System. Web >
...
</ Configuration >

AboveCodeFour key points have been modified:

1. Change enablepasswordretrieval from false to true. You can retrieve the password.

2. Change enablepasswordreset was from true to false. That is, do not reset the password.

3. Added passwordformat = "encrypted ".

4. The machinekey is generated for encryption.

After configuring the config, we will create a model for forgot password View. This class should be placed in the accountmodel. CS class.

 Using System;
Using System. Collections. Generic;
Using System. componentmodel. dataannotations;
Using System. Globalization;
Using System. Web. MVC;
Using System. Web. Security;
Namespace Mvcapplication. Models
{
Public Class Changepasswordmodel
{
...
}
Public Class Logonmodel
{
...
}
Public Class Registermodel
{
...
}
Public Class Forgotpasswordmodel
{
[Required]
[Datatype (datatype. emailaddress)]
[Display (name = " Email Address " )]
Public String Email { Get ; Set ;}
}
}

Build a project before adding a new view. Expand the view folder, right-click Add-> View. Name it forgotpassword. This view will be strongly typed and correspond to the previously created forgotpasswordmodel.

After adding the view, add a form. It accepts the user's email address.

@ Model mvcapplication. Models. forgotpasswordmodel
@{
Viewbag. Title = " Forgotpassword " ;
}
<H2> forgotpassword </H2>
1.6 Retrieving a forgotten password | 27
<P>
Use the form below to retrieve your password.
</P>
<SCRIPT src = " @ URL. Content ( " ~ /Scripts/jquery. Validate. Min. js " ) "
Type =" Text/JavaScript " > </SCRIPT>
<SCRIPT src = " @ URL. Content (
" ~ /Scripts/jquery. Validate. unobtrusive. Min. js " ) "
Type = " Text/JavaScript " > </SCRIPT>
@ Using (html. beginform ()){
@ Html. validationsummary (True , " Password retrieval was
Unsuccessful. Please correct the errors and Try Again. " )
<Div>
<Fieldset>
<Legend> account information </legend>
<Div Class = " Editor-label " >
@ Html. labelfor (M => M. Email)
</Div>
<Div Class = " Editor-field " >
@ Html. textboxfor (M => M. Email)
@ Html. validationmessagefor (M => M. Email)
</Div>
<P>
<Input type = " Submit " Value = " Retrieve Password " />
</P>
</Fieldset>
</Div>
}

Then update the file in the previous article.ArticleThe mailclient class we created. Add a new function. The password they forgot will be sent to users:

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. net. mail;
Using System. net;
Using System. configuration;
Namespace Mvcapplication. utils
{
Public Class Mailclient
{
Private Static Readonly Smtpclient client;
Static Mailclient ()
{
...
}
Private Static Bool Sendmessage ( String From , String To,
String Subject, String Body)
{
...
}
Public Static Bool Sendwelcome ( String Email)
{
...
}
Public Static Bool Sendlostpassword ( String Email,
String Password)
{
String Body = " Your password is: " + Password;
Return Sendmessage ( " No-reply@no-reply.com " , Email,
" Lost Password " , Body );
}
}
}

This is very similar to the previous one. Except for the second parameter-user password. Put the password in the body and send it to the user.

Finally, create two actions in the accountcontroller. The first is to simply read the previous view. The second one can receive the post forgotpasswordmodel. Using the email address we collected in form, we can find the corresponding user in the member database. Then, send the password to the email address.

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using System. Web. Routing;
Using System. Web. Security;
Using Mvcapplication. models;
Using Mvcapplication4.utils;
Namespace Mvcapplication4.controllers
{
Public Class Accountcontroller: Controller
{
...
//
// Get:/account/forgotpassword
Public Actionresult forgotpassword ()
{
Return View ();
}
//
// Post:/account/forgotpassword
[Httppost]
Public Actionresult forgotpassword (
Forgotpasswordmodel Model)
{
If (Modelstate. isvalid)
{
Membershipusercollection users =
Membership. findusersbyemail (model. Email );
If (Users. Count> 0 )
{
Foreach (Membershipuser user In Users)
{
Mailclient. sendlostpassword (model. email,
User. GetPassword ());
}
Return Redirecttoaction ( " Logon " );
}
}
// If we got this far, something failed,
// Redisplay form
Return View (model );
}
...
}
}

In the last two recipes. The basic email has been sent to the user. These examples can be further improved to sending more complex emails. Even the email content can include HTML. In the mail message class, there is a bool type variable isbodyhtml that can be set. Whether HTML content can be sent.

 

For more information, see

Membership. Providers Property

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.