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. However, he 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>

The above code modifies four key points:

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

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 MailClient class we created in the previous article. 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,

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

 

Author technical brother

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.