当前位置:网站首页>Quickly master asp Net authentication framework identity - user registration

Quickly master asp Net authentication framework identity - user registration

2022-06-22 17:04: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

46acd8c7757979144a8f344273565dee.png

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 .

5a8f805151b658c18bcc9cf63938bb4c.png

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. ▼▼

5bc5756b77a8671cb9d5d29913cf1172.gif

If you like my article , that

Watching and forwarding is my greatest support !

( Stamp the blue words below to read )

d07925ccd5e268e0814287d660691a6c.png

Recommends WeChat official account : Code Xia Jianghu

                        8b2e3e41862831cde44bda4b32836e69.png I think it's good , Point and watch before you go

原网站

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221536306815.html