20 tips for ASP. net mvc 3 Development (6) [20 recipes for programming MVC 3]: retrieve forgotten passwords

Source: Internet
Author: User
Tags lost password

Topics

You or a user registered on your website cannot remember your password. You need a way to retrieve it.

 

Solution

Add a new action and view to the accountcontroller so that users can retrieve their passwords. Use the membership class to search for and match users, and send an email containing a password.

 

Discussion

By default, MVC Internet applicationsProgramOne-way hash that cannot be reversedAlgorithm. In the following example, two-way hash encryption is used by default. This method is not safe, but you can avoid forcing users to change their passwords when they forget their passwords.

First, adjust the membership node settings in the web. config file:

 <?  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 >

For the above settingsCode, We have four changes:

    1. Change enablepasswordretrieval to true;
    2. Change enablepasswordreset to false;
    3. Add passwordformat = "encrypted ";
    4. Generate an encrypted machinekey;

After the configuration information is modified, add a new action to the accountmodels. CS class and create a view that forgets the password:

 Using System;
Using System. Collections. Generic;
Using System. componentmodel. dataannotations;
Using System. Globalization;
Using System. Web. MVC;
Using System. Web. Security;

Namespace Mvcapplication4.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 ;}
}
}

Before creating a new view, the application must be compiled. Click Generate-> Generate solution or press F6. After compilation, expand the views folder, right-click the "Account" folder, and choose "add"> "View" (1-4 ). Change the view name to "forgotpassword", select the "Create strong view" option, select the previously created "forgotpasswordmodel" from the "model class" drop-down box, and click "add ".

After the view is created, add a basic form that allows you to enter the email address you entered during registration:

@ Model mvcapplication4.models. forgotpasswordmodel
@{

Viewbag. Title = "forgotpassword ";
}

< H2 > Forgotpassword</ H2 >
< 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 >
}

Next, we will add a new method to the previously created mailclient class to send users' forgotten passwords:

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. net. mail;
Using System. net;
Using System. configuration;

Namespace Mvcapplication4.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 method is very similar to the previous method (* Translator's note: The method for sending a welcome email), but adds another parameter-the user's password. The password will be added to the email content and sent to the user.

Finally, add two forgotpassword methods to accountcontroller. The first method is the default loading action, and the second is to accept the data sending and returning action after the user fills in the email address, he will search for and match the email address in the database to find the user, and then send the user password to the user through this 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 Mvcapplication4.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 previous two tips, I only sent some basic information to the user. Set isbodyhtml of mailmessage to true. HTML or more complex content can be sent to users through simple extension enhancement.

 

Reference

Membership. Providers Property Source Book Address Source Code

Related Article

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.