Identity application of ASP. Net core (Part 1)

Time:2021-8-2

1、 Foreword

In the introduction of the previous chapter, I briefly introducedIdentityServer4The persistent storage mechanism related configuration and operation data, realized data migration, but did not explain the persistent operation to users. We also mentioned in the summary,

becauseIdentityServer4This supports access to other authentication methods, so you can make reasonable adjustments according to your needsextendFor example, we can useIdentity of ASP. Net coreIdentity authentication mechanismImplementation extension, realize the user data persistence operation.

Of course, this article is put aside for the time beingIdentityServer4This topic, but to meet aloneIdentity of ASP. Net coreWhat is the identity authentication mechanism?

Therefore, this article mainly introduces the practical application of asp.net core identity.

2、 First acquaintance

Asp.net core identity is an identity authentication system used to build asp.net core web applications, including user data, user identity and registered login information data storage, which can enable your application to have login function and continuously store login user related data.

Asp.net core identity (hereinafter referred to as identity) can be a simple user management system, but it is a powerful system, including all aspects of user management, mainly including:

  1. User data storage (use any relational database you like, from sqllite to MySQL, sqlserver, etc., supported by Entity Framework)
  2. Login, registration and identity authentication (cookie based identity authentication. If you use VS, you can also generate user interface and processing code for registration and login)
  3. Role management
  4. Declaration based authentication mode

Specifically forIdentityFor your understanding, please refer toGetting started with identity for ASP. Net core

Next, we will mainly practice and apply it to understandIdentity

3、 Practice

3.1 create project

Create asp.net core web application based on vs2019. Net core 3.1.

3.1.1 process:

1. Select File > New > project.
2. Select "asp.net core web application". Naming the project webidentitydemov3.0 has the same namespace as the project download. Click OK.
3. Select the asp.net core web MVC application, and then select change authentication.
4. Select a single user account and click OK.

Generated projectASP.NET Core IdentityIn the form of class library Razor Provide.

img

3.1.2 directory structure:

img

3.1.3 migrating data

Find the appsettings.json file and the database connection string of connectionstrings. The default is to connect to the local database. Of course, you can also change it to the database address you specify.

"ConnectionStrings": {
   "DefaultConnection": "Data Source=.;initial catalog=IdentityV3;user id=sa;password=123456;"
  },

Synchronize to the database based on the generated migration code

PM> Update-Database

img

Here, we’re almost doneIdentityAfter the project is set up, you can log in and register here.

3.1.4 the effects are as follows:

img

However, looking back at the generated directory structure, I found that there was noIdentityUser related model, cshtml and other files. Why?

In fact, these related files have been provided by the built-in razor class library. Therefore, the generated code directory does not exist.

However, in the actual development, we need to generate the corresponding source code to expand and change the code and behavior according to the development requirements. Therefore, files that need to be rewritten can be generated according to the scaffold identity provided by net core.

3.2 base frame identification

Asp.net core identity is provided as razor class library in asp.net core 2.1 and later versions. Applications containing identity can apply the base frame to selectively add the source code contained in the identity razor class library (RCL).

3.2.1 process:

1. From the corresponding item, right-click the item > Add > new base frame item.

2. From the add base frame dialog box in the left pane, select identification > Add.

3. In the add ID dialog box, select the desired option.

Next, using the existing data context, select all files for later rewriting, as shown below.

Here is an example, so I chose to add onlyRegisterLoginLogOutandRegisterConfirmationfile

img

3.2.2 effect:

After generation, the directory will add changes:

img

It can be found that inAreasDirectory, generatedRazor PageFile, note that this is not an MVC view controller.

Just introduced, this is because asp.net core identity is provided as a razor class library in asp.net core 2.1 and later versions, which is no longer the previous 2.0 class library, because it is based on razor page,

So we can’t find the original version 2.0Controllers(e.gAccountEtc.)

At this time, if you want to the page or code, you need to rewrite the file into your project based on the base frame, and then make specific modifications.

However, if you want to implement the MVC view controller, you can generate the corresponding controller and business logic based on the rewriting in razor page to implement the view controller.

4、 Distinction

Version 2.0

See someone ask: where is the account controller in the identity area after personal authentication is selected in the. Net core MVC template?

In fact, this is because asp.net core identity is provided as a razor class library in asp.net core 2.1 and later versions, which is no longer the previous 2.0 class library. Because it is based on razor page, it can not be found in the original 2.0 versionControllers(e.gAccountEtc.)

However, if you want to implement the MVC view controller, you can generate the corresponding controller and business logic based on the rewriting in razor page to implement the view controller. Of course, you can also use the 2.0 project for reference to rewrite your business.

4.1 create project

Create asp.net core web application based on vs2019. Net core 2.0.

4.1.1 process:

1. Select File > New > project.
2. Select "asp.net core web application". Naming the project webidentitydemov 2.0 has the same namespace as the project download. Click OK.
3. Select the asp.net core web MVC application, and then select change authentication.
4. Select a single user account and click OK.

Generated projectASP.NET Core IdentityIn the form of class library Razor Provide.

img

4.1.2 directory structure:

img

It can be found that in our choiceWhen personal identity authenticationIdentity is automatically added to the project and generated

  • Account controllerAccountControllerRegistration and login related codes are here)
  • Log in to the registration page(there are others, such as confirmation email, restricted access, etc.)
  • Management controller(ManageControllerThis is for registered users. It mainly has two functions: password change and two factor authentication)

MVC has emerged as a view controller, and the corresponding controller method can also be found. This is also different from upgrading to version 2.1 and later.

After the MVC view controller mode in version 2.0 is upgraded to version 2.1 and later, the razor class library is directly adopted, and the controller is written to the cshtml file instead.

4.1.3 migrating data:

Find the appsettings.json file and the database connection string of connectionstrings. The default is to connect to the local database. Of course, you can also change it to the database address you specify.

"ConnectionStrings": {
   "DefaultConnection": "Data Source=.;initial catalog=IdentityV2;user id=sa;password=123456;"
  },

Synchronize to the database based on the generated migration code

PM> Update-Database

Here, we have basically completed version 2.0IdentityThe project has been set up. You can run it, log in and register.

Here, we will experience ASP. Net core2.0 and the changes after upgrading to version 2.1 and later.

5、 Expand

5.1 configuration issues

5.1.1 default configuration:

Here is the codeIdentityThe default option configuration of the service provides the application through dependency injection.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext(options =>
        options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
          //Note that the options.signin.requireconfirmedaccount setting item is set to true by default,
         //In this case, the newly registered user needs to confirm to complete the registration. If the mail system is not installed, this step cannot be completed, so it is changed to false here.
        services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = false)
        .AddEntityFrameworkStores();
    services.AddControllersWithViews();
    services.AddRazorPages();
}

Enable by callingUseAuthenticationUseAuthenticationWill authenticatemiddleware Add to request pipeline.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

In addition to the above default configuration options, you can also limit the user name according to your business requirements, such as some want to limit the user name, some need to limit the password, etc.

A typical pattern is to call allAdd{Service}Method, then call allservices.Configure{Service}method.

5.1.2 custom configuration:

a. Configure user name:

services.AddDefaultIdentity(options =>
{
    options.User = new UserOptions
    {
        Requireuniqueemail = true, // unique email is required
        Allowedusernamecharacters = "abcdefgabcdefg" // allowed user name characters. The default is abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 [email protected]+
    };
});

Regular expressions are not supported. If you need to support Chinese characters, you may need to add many Chinese characters..

b. Configure password:

services.AddDefaultIdentity(options=>
{
    options.Password = new PasswordOptions
    {
        Requiredigit = true, // a number between 0 and 9 is required. The default is true
        Requiredlength = 8, // the minimum password length is required. The default is 6 characters
        Requirelewercase = true, // lowercase letters are required. The default is true
        Requirenoalphanumeric = true, // special characters are required, and the default is true
        Requireduniquechars = 3, // the number of non repeating characters in the password is required. The default is 1
        Requireuppercase = true // capital letters are required. The default is true
    };
})

c. Lock account

services.AddDefaultIdentity(options=>
{
    options.Lockout = new LockoutOptions
    {
        Allowedfornewusers = true, // the new user locks the account. The default is true
        Defaultlockouttimespan = timespan. Fromhours (1), // lock duration: 5 minutes by default
        Maxfailedaccessattempts = 3 // login errors. The maximum number of attempts is 5 by default
    };
})

d. Database storage

services.AddDefaultIdentity(options=>
{
    options.Stores = new StoreOptions
    {
        Maxlengthforkeys = 128, // the maximum length of the primary key
        Protectpersonaldata = true // to protect user data, implement the iprotecteduserstore interface
    };
})

If not set, the primary key is the string length of max.

e. Token configuration

services.AddDefaultIdentity(options=>
{
    options.Tokens = new TokenOptions
    {
         Authenticatortokenprovider = "myauthenticatortokenprovider", // used to verify dual login by using verifier.
         Changeemailtokenprovider = "mychangeemailtokenprovider", // used to generate the token used in the email change confirmation email.
          Changephonenumbertokenprovider = "mychangephonenumbertokenprovider", // used to generate the token used when changing the phone number.
          Emailconfirmationtokenprovider = "myemailconfirmationtokenprovider", // the token provider used to generate the token used in the account confirmation email.
         Passwordresettokenprovider = "mypasswordresettokenprovider" // used to generate the token used in password reset email
        Providemap = new dictionary(), // construct the user token provider as the key of the provider name.
        Authenticatorissuer = "identity", // authenticated consumer      
    };
})

How to generate a token, and then how to send the token to the user to request user authentication.

f. Claim configuration

services.AddDefaultIdentity(options=>
{
    options.ClaimsIdentity = new ClaimsIdentityOptions
    {
        Roleclaimtype = "identityrole", // declaration type used for role declaration.
        Useridclaimtype = "identityid", // declaration type used for user identifier declaration.
        Securitystampclaimtype = "securitystamp", // declaration type used for security stamp declaration.
        Usernameclaimtype = "identityname" // declaration type used for user name declaration.
    };
})

g. Login configuration:

services.AddDefaultIdentity(options=>
{
    options.SignIn = new SignInOptions
    {
        Requireconfirmedemail = true, // the mailbox is required to be activated. The default is false
        Requireconfirmedphonenumber = true // you need to activate your phone number to log in. The default is false
    };
})

When logging in, you cannot log in if your mobile phone number or email address is not activated / confirmed.

services.ConfigureApplicationCookie(options =>
{
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.Cookie.Name = "YourAppCookieName";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
    options.LoginPath = "/Identity/Account/Login";
    // ReturnUrlParameter requires 
    //using Microsoft.AspNetCore.Authentication.Cookies;
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});

Configure application cookies inStartup.ConfigureServices。 Configureapplication cookie must be called after calling orAddIdentity``AddDefaultIdentity

i. Password hasher settings:

services.Configure(option =>
{
    option.IterationCount = 12000; // The number of iterations used when hashing passwords using pbkdf2.
});

Passwordhasheroptions gets and sets options for password hashing.

j. Global requires all users to be authenticated

services.AddAuthorization(options =>
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    });

6、 Summary

  1. This article briefly introducesIdentity of ASP. Net core, a component library responsible for authenticating the user’s identity, and carried out relevant practical application experience at the same time.
  2. The user defined identity and table structure will be described later.
  3. If there is something wrong or incomprehensible, I hope you can make more corrections, ask questions, discuss together, keep learning and make common progress.
  4. Project address

7、 Attach

Introduction to ASP. Net core identity

Configuring asp.net core identity

Getting started with identity for ASP. Net core