当前位置:网站首页>Quickly master asp Net authentication framework identity - reset password by mail
Quickly master asp Net authentication framework identity - reset password by mail
2022-06-27 03:47:00 【Dotnet cross platform】
This is a ASP.NET Core Identity The fourth article in the series , The last article explained how to ASP.NET Core Identity Realize user login and logout in .
This article talks about how to ASP.NET Core Identity To reset the password of the user account through the mail service .
Click on the blue word above or behind , read ASP.NET Core Identity Collection of series .
The sample project for this article :https://github.com/zilor-net/IdentitySample/tree/main/Sample04

Password reset
The most common function in user management is password reset .
Password reset process , System administrators should not be involved , Because the user should be able to complete the whole process independently .
Usually , The login page will provide users with a link to forget their password , To reset the password , This is what we will do next .
Briefly explain the password reset process :
The user clicks the forgot password link , Then jump to the page with the email field .
After the user fills in this field , The application will send a password reset connection to this email .
The user clicks the password reset link in the email , The password reset token is used , Redirect to password reset page .
After the user fills in all the fields in the form , The application will reset the password , The user is redirected to the login page or home page .
The mail service
The mail service has been integrated in the sample project 「EmailService」 , To help us send mail ,
The specific implementation of email sending is not the subject of this series , Don't elaborate too much . You can check the examples by yourself 「EmailService」 The code about mail sending in the project .
The mail service is registered in the dependency injection framework through the extension method , The specific configuration is shown in 「appsettings.json」 in .
Forget the password
First , We need to create 「 Forget the password 」 The view of .
stay 「Models」 In the folder , Create a 「ForgotPasswordModel」 class :
public class ForgotPasswordModel
{
[Display(Name = " email ")]
[Required(ErrorMessage = " Email cannot be empty ")]
[EmailAddress(ErrorMessage = " Incorrect email format ")]
public string Email { get; set; }
}It will be used in 「 Forget the password 」 In the view , Here we just need to get the user's email , So there's only one 「Email」 attribute .
Next , stay 「Account」 The controller , Create two operation methods :
[HttpGet]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordModel forgotPasswordModel)
{
return View(forgotPasswordModel);
}
public IActionResult ForgotPasswordConfirmation()
{
return View();
}We are already familiar with this routine , first 「ForgotPassword」 Just to create views ; the second 「ForgotPassword」 To implement logic ;「ForgotPasswordConfirmation」 Return to the confirmation view .
Next , Then create related views in turn :

<h1>ForgotPasswordConfirmation</h1>
<p>
A link to reset your password has been sent to your email address !
</p>And then in 「Login」 In the view , Add a link to forget your password :
<div class="form-group">
<a asp-action="ForgotPassword"> Forget the password </a>
</div>Now? , Let's implement the logic of forgetting the password :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword([FromServices]IEmailSender emailSender, ForgotPasswordModel forgotPasswordModel)
{
if (!ModelState.IsValid)
return View(forgotPasswordModel);
var user = await _userManager.FindByEmailAsync(forgotPasswordModel.Email);
if (user == null)
return RedirectToAction(nameof(ForgotPasswordConfirmation));
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
var callback = Url.Action(nameof(ResetPassword), "Account", new { token, email = user.Email }, Request.Scheme);
var message = new Message(new string[] { user.Email }, " Reset password ", callback, null);
await emailSender.SendEmailAsync(message);
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}If the model is valid , Just through the user's email , Get users from the database .
If it doesn't exist , Just put the user , Redirect to the confirmation page where the message has been sent , Instead of creating a message that the user does not exist .
This is mainly done for security reasons , To prevent someone from using this feature , Verify the validity of the user name .
If the user exists , Just through 「GeneratePasswordResetTokenAsync」 Method , Generate a token , And create a callback link , To the operation we will use to reset the password logic .
Last , E-mail we provide to users , Send a mail message , And redirect the user to the confirmation page .
Now? , The program has not been able to create a token , Because we haven't registered the token service yet , This needs to be registered 「Identity」 Method :
builder.Services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders();If we want the password reset token to be valid only for a limited time , for example : 2 Hours , Then we need to configure the token lifetime :
builder.Services.Configure<DataProtectionTokenProviderOptions>(opt =>
opt.TokenLifespan = TimeSpan.FromHours(2));Reset password
next , So let's do that 「ResetPassword」 How to reset the password , Create a 「ResetPasswordModel」 class :
public class ResetPasswordModel
{
[Display(Name = " password ")]
[Required(ErrorMessage = " The password cannot be empty ")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = " Confirm the password ")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = " The password does not match the confirmation password .")]
public string ConfirmPassword { get; set; }
public string Email { get; set; }
public string Token { get; set; }
}then , stay 「Account」 The controller , establish 「ResetPassword」 Operation method :
[HttpGet]
public IActionResult ResetPassword(string token, string email)
{
var model = new ResetPasswordModel { Token = token, Email = email };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordModel resetPasswordModel)
{
return View();
}
[HttpGet]
public IActionResult ResetPasswordConfirmation()
{
return View();
}Here with 「ForgotPassword」 The operation is similar to .
「HttpGet」ResetPassword The operation will accept messages from the e-mail , Password reset connection request , Extract tokens and e-mails , And create a view .
「HttpPost」ResetPassword The operation is the logic that handles resetting the password .
ResetPasswordConfirmation Just a password reset confirmation view .
Create these views in turn :

It should be noted that , We need to take 「Email」 and 「Token」 Two fields are hidden , Because these two values are provided by the application , No user settings are required :
<input type="hidden" asp-for="Email" class="form-control" />
<input type="hidden" asp-for="Token" class="form-control" />「ResetPasswordConfirmation」 View :
<h1>ResetPasswordConfirmation</h1>
<p>
Your password has been reset . Please click here <a asp-action="Login"> Sign in </a>!
</p> Last , Then revise 「POST」ResetPassword Operation method :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordModel resetPasswordModel)
{
if (!ModelState.IsValid)
return View(resetPasswordModel);
var user = await _userManager.FindByEmailAsync(resetPasswordModel.Email);
if (user == null)
RedirectToAction(nameof(ResetPasswordConfirmation));
var resetPassResult = await _userManager.ResetPasswordAsync(user, resetPasswordModel.Token, resetPasswordModel.Password);
if(!resetPassResult.Succeeded)
{
foreach (var error in resetPassResult.Errors)
{
ModelState.TryAddModelError(error.Code, error.Description);
}
return View();
}
return RedirectToAction(nameof(ResetPasswordConfirmation));
}First , Check the validity of the model , And whether the user exists in the database .
after , Use 「ResetPasswordAsync」 Method , Perform password reset operation .
If the operation fails , Just add an error to the model state and return to the view . otherwise , We redirect the user to the confirmation page .
It should be noted that , If you want to test the final effect , The configuration of the mail service and the email address of the user must be true and valid .
Summary
Now? , We have implemented the user via email , Function of resetting password , The next article will explain how to register users , Must confirm whether email is a valid function .
More highlights , Please pay attention to me. ▼▼

If you like my article , that
Watching and forwarding is my greatest support !
( Stamp the blue words below to read )ASP.NET 6 The most easy to understand dependency injection series
Check and fill gaps, and learn from the system EF Core 6 series

Recommends WeChat official account : Code Xia Jianghu
I think it's good , Point and watch before you go
边栏推荐
- Ldr6028 OTG data transmission scheme for mobile devices while charging
- 面对AI人才培养的“产学研”鸿沟,昇腾AI如何做厚产业人才黑土地?
- Usage knowledge of mobile phones in new fields
- 2016Analyzing the Behavior of Visual Question Answering Models
- Promise source code class version [III. promise source code] [detailed code comments / complete test cases]
- 2019LXMERT:Learning Cross-Modality Encoder Representations from Transformers
- 超级详细,2 万字详解,吃透 ES!
- 栈溢出漏洞
- Argo Workflows —— Kubernetes的工作流引擎入门
- Pat grade a 1023 have fun with numbers
猜你喜欢

GAMES101作业7提高-微表面材质的实现过程

Kotlin Compose 隐式传参 CompositionLocalProvider

敏捷开发篇--Agile Development-自用

PostgreSQL基础命令教程:创建新用户admin来访问PostgreSQL

文旅夜游|以沉浸式视觉体验激发游客的热情

Pat class a 1024 palindromic number

fplan-Powerplan实例

How can e-commerce products be promoted and advertised on Zhihu?

记录unity 自带读取excel的方法和遇到的一些坑的解决办法

ERP需求和销售管理 金蝶
随机推荐
静态时序分析-OCV和time derate
与STM32或GD32替换说明
Nestjs environment variable configuration to solve the problem of how to inject services into interceptors
Description of replacement with STM32 or gd32
Stack overflow vulnerability
Super detailed, 20000 word detailed explanation, thoroughly understand es!
Anaconda3安裝過程及安裝後缺失大量文件,沒有scripts等目錄
Questions and answers of chlor alkali electrolysis process in 2022
为什么 C# 访问 null 字段会抛异常?
【一起上水硕系列】Day 6
MATLAB | 基于分块图布局的三纵坐标图绘制
百度飞桨“万有引力”2022首站落地苏州,全面启动中小企业赋能计划
jmeter将上一个请求的结果作为下一个请求的参数
Overview of Tsinghua & Huawei | semantic communication: Principles and challenges
再探Handler(上)(Handler核心原理最全解析)
Pat grade a 1019 general palindromic number
ESP8266
Promise source code class version [III. promise source code] [detailed code comments / complete test cases]
2021:Greedy Gradient Ensemble for Robust Visual Question Answering
Ledrui ldr6035 usb-c interface device supports rechargeable OTG data transmission scheme.