当前位置:网站首页>Quickly master asp Net authentication framework identity - user registration
Quickly master asp Net authentication framework identity - user registration
2022-06-22 03:46:00 【Dotnet cross platform】
Recommended attention 「 Code Xia Jianghu 」 Add Star standard , Never forget the Jianghu Affairs
This is a ASP.NET Core Identity The second article in the series , The last article introduced Identity Integration of framework , And some basic knowledge .
This article talks about how to ASP.NET Core Identity User registration in .
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/Sample02

preparation
ASP.NET Core Identity There are many different identity options , Help us achieve user registration .
First , Let us in 「Models」 In the folder , Create a user registration model :
public class UserRegistrationModel
{
[Display(Name = " surname ")]
public string FirstName { get; set; }
[Display(Name = " name ")]
public string LastName { get; set; }
[Display(Name = " email ")]
[Required(ErrorMessage = " Email cannot be empty ")]
[EmailAddress]
public string Email { get; set; }
[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; }
}Properties in this class , Users are required to fill in the registration form .
among ,Email and Password Properties are required ,ConfirmPassword The value of the property must be the same as Password The value of the property matches .
With this model , Let's create another 「Account」 controller :
public class AccountController : Controller
{
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register(UserRegistrationModel userModel)
{
return View();
}
} It has two Register Operation method , Used to provide user registration function .
first Register Method acceptance Get request , View used to display the registration form ;
the second Register Method acceptance Post request , Used to handle user registration logic , And display a view of the registration results .
Also need to GET Register operation , Create a view , Here we can use Create Templates , Model class selection UserRegistrationModel The class can .

Now the form in this view , It is already possible to register models for users , All input fields are provided .
It should be noted that , We'd better modify the form asp-validation-summary The value of is All.
because , By default , It can only display error messages generated by model validation , It will not display the validation errors we set ourselves .
In the view Create Button , Will jump to POST Requested Register Operation method , And populate the user registration model .
stay Web API Using data from users in , It is better to use the method of data transmission object , But in MVC This is not necessarily the case in .
This is because MVC There are models , With views , The model to some extent , It replaces the responsibility of data transmission objects .
Because our data is passed through views , So this kind of model is also called view model .
「UserRegistrationModel」 Is a view model , If we want to really store it in the database , It must be mapped to User Entity class .
We need to install AutoMapper :
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection then , stay Program Class :
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());next , On the navigation menu of the layout page , Add a registration button .
Because the login button will be added later , So for code maintainability , We can create a partial view :
// Shared\_LoginPartial.cshtml
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Account"
asp-action="Register"> register </a>
</li>
</ul>Last , modify 「_Layout.cshtml」 Layout view , Add login distribution view on the navigation menu :
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<partial name="_LoginPartial" /><!-- add to -->
<ul class="navbar-nav flex-grow-1">Register operation
The preparatory work has been completed .
Now? , Let's start with the user registration logic .
First , Must be in 「Account」 The controller , Inject AutoMapper and UserManager class :
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
public AccountController(IMapper mapper, UserManager<User> userManager)
{
_mapper = mapper;
_userManager = userManager;
}「UserManager」 from Identity Framework provide , It is responsible for helping us manage users in our applications .
The user registration logic is in Post Requested Register Method implementation :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(UserRegistrationModel userModel)
{
if(!ModelState.IsValid)
{
return View(userModel);
}
var user = _mapper.Map<User>(userModel);
var result = await _userManager.CreateAsync(user, userModel.Password);
if(!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.TryAddModelError(error.Code, error.Description);
}
return View(userModel);
}
await _userManager.AddToRoleAsync(user, "Guest");
return RedirectToAction(nameof(HomeController.Index), "Home");
}What needs to be noted here is , We changed this method to asynchronous , because ·UserManager· The helper method of is also asynchronous .
Inside the method , First check the validity of the model , If it is invalid , Return the same view with invalid model .
If the inspection passes , will userModel Shoot to user Entity .
Use CreateAsync Method to register users , It hashes the password and saves it .
after , Check the creation result it returns .
If created successfully , We just need to UserManager With the help of the , Use AddToRoleAsync Method , Add a default role to the user , And redirect the user to Index page .
But if the registration fails , Just go through all the errors , And add them to ModelState in .
Previously, we have changed the validation information summary of the view to All, Otherwise, the error added here , It doesn't show up .
Last , Don't forget to create AutoMapper Mapping configuration class for :
// MappingProfile.cs
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<UserRegistrationModel, User>()
.ForMember(
user => user.UserName,
expression => expression.MapFrom(userModel => userModel.Email));
}
}Here we map email to user name , Because we do not provide the field of user name in the registration form .
Now start the application , Test the user registration .
I can try all kinds of wrong registration content , Observe the verification results .
It should be noted that , Default password verification rules , Very complicated , It requires not only upper and lower case letters , You must also have a special symbol .
This password rule is very good , But sometimes I may not need strong rules .
And we used email as the username , But by default , There is no requirement that email is the only .
therefore , We can change these rules , This needs to be registered Identity The place of , Modify through configuration options :
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequiredLength = 6;
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationContext>();such as , We have eliminated the numbers here 、 Verification of capital letters and special characters , The minimum length is changed to 6 position , At the same time, set the unique verification of e-mail .
Now let's start the application , Test the registration process , For example, the wrong password format 、 Duplicate email .
Through some tests, we can find , Some error messages are in Chinese 、 Some are in English .
Because there are two types of errors , One is our custom model validation error , We have set the error message , So this type is Chinese .
The other is ASP.NET Core Identity Built in validation error , It is through the operation method , Read and add to the model state by yourself .
because ASP.NET Core Identity It's in English , So what we get is information in English ,
however , We can also define Chinese information by ourselves , This requires us to create a custom error description class :
public class CustomIdentityErrorDescriber : IdentityErrorDescriber
{
public override IdentityError PasswordTooShort(int length)
{
return new()
{
Code = nameof(PasswordTooShort),
Description = $" The password needs at least {length} position "
};
}
public override IdentityError DuplicateEmail(string email)
{
return new()
{
Code = nameof(DuplicateUserName),
Description = $" email {email} Already exists ."
};
}
public override IdentityError DuplicateUserName(string username)
{
return new()
{
Code = nameof(DuplicateUserName),
Description = $" user name {username} Already exists ."
};
}Custom error messages , Need to override 「IdentityErrorDescriber」 Wrong method of base class , Set the error description you want .
If necessary , You can read the source code , Find all the wrong methods .
We also need to configure it to register Identity In the service approach :
AddErrorDescriber<CustomIdentityErrorDescriber>()Summary
Now? , We have implemented user registration , See the example project for the specific code , The next article will continue to explain user login and identity authentication .
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
边栏推荐
- Key program of TwinCAT 3 RS232 communication
- A component required a bean of type 'com. example. demo3.service. UserServiceImp' that could not be fou
- [网鼎杯 2018]Fakebook1 参考
- Ads communication between Beifu twincat3 controller and controller
- std::make_ Shared features
- docker 安装redis
- How to break through the sales dilemma of clothing stores
- IIR滤波器设计基础及Matlab设计示例
- Beifu TwinCAT 3 cylinder action program compilation
- Direct insertion sort of eight sorts
猜你喜欢

Flutter 性能优化

Use yolov5 to train your own data set; Installation and use of yolov5; Interpretation of yolov5 source code

Flutter 颜色渐变及模仿淘宝渐变关注按钮

Based on logback XML to realize the insensitive operation of saving log information

平衡二叉树——调整变换规则

Direct insertion sort of eight sorts

如何快速定位bug和编写测试用例?

我们如何解决了RealSense偏色问题?

The future has come: cloud primary Era

3DE new simulation status
随机推荐
MySQL 45 lecture learning notes (II) execution of SQL update statements
Dart异步是怎麼實現
SSM住院管理系统
倍福TwinCAT3中PLC程序变量定义和硬件IO关联
VIM common commands
128陷阱——源码分析
A component required a bean of type 'com. example. demo3.service. UserServiceImp' that could not be fou
WPF 实现星空效果
多线程 interrupt用法
MySQL index creation, optimization analysis and index optimization
试用了多款报表工具,终于找到了基于.Net 6开发的一个了
Sword finger offer 68 - ii Nearest common ancestor of binary tree
MySQL 45 lecture notes (I) execution of an SQL statement
Rabbmitmq publishing keyword mode < 3 >
Pointer and pointer of pointer
Flutter-Stream使用
IIR滤波器设计基础及Matlab设计示例
动态规划-使用最小花费爬楼梯为例
Mysql 45讲学习笔记(一)一条sql语句的执行
嵌入式软件测试的经验经历和总结