Deep understanding of Identity (1) and aspnetidentity of Aspnet Core

Source: Internet
Author: User
Tags two factor

Deep understanding of Identity (1) and aspnetidentity of Aspnet Core

I recently learned about asp. netcore is going to write it out to share with you. I plan to write the Identity part first, which will begin with asp. netore identity is a simple and practical start, and then explains the main classes and customize these classes.

Topic: simple and practical project creation for asp. netcore Identity:

Use the asp. netcore Project template to create an empty (empty) project. After the project is created, edit the. csproj file. The Code is as follows:

<Project Sdk="Microsoft.NET.Sdk.Web">  <PropertyGroup>    <TargetFramework>netcoreapp2.0</TargetFramework>  </PropertyGroup>  <ItemGroup>    <Folder Include="wwwroot\" />  </ItemGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"        Version="2.0.0" />  </ItemGroup></Project>

Added

<DotNetCliToolReference Include = "Microsoft. EntityFrameworkCore. Tools. DotNet"

Version = "2.0.0"/> This line of code;
Edit the startup code file and add the mvc and authentication sections.
public void ConfigureServices(IServiceCollection services) {            services.AddMvc();}        public void Configure(IApplicationBuilder app) {            app.UseStatusCodePages();            app.UseDeveloperExceptionPage();            app.UseStaticFiles();            app.UseMvcWithDefaultRoute();}
Configure Identity

Now we configure the identity information, including the configuration modification and adding the user class.

1. Create a user class

The user class represents the user's account information, such as the login name, password, role, email, and other information. The Code is as follows:

using Microsoft.AspNetCore.Identity;namespace DemoUser.Models{    public class AppUser:IdentityUser    {            }}

We inherit the identityuser class. This class already contains basic user information attributes, such as the login name, password, and mobile phone number. The decompiled information of this class is as follows:

// Decompiled with JetBrains decompiler// Type: Microsoft.AspNetCore.Identity.IdentityUser`1// Assembly: Microsoft.Extensions.Identity.Stores, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60// MVID: 7E04453E-9787-4C8F-ACD1-4ADA9BB7C88C// Assembly location: /usr/local/share/dotnet/sdk/NuGetFallbackFolder/microsoft.extensions.identity.stores/2.0.1/lib/netstandard2.0/Microsoft.Extensions.Identity.Stores.dllusing System;namespace Microsoft.AspNetCore.Identity{  /// <summary>Represents a user in the identity system</summary>  /// <typeparam name="TKey">The type used for the primary key for the user.</typeparam>  public class IdentityUser<TKey> where TKey : IEquatable<TKey>  {    /// <summary>    /// Initializes a new instance of <see cref="T:Microsoft.AspNetCore.Identity.IdentityUser`1" />.    /// </summary>    public IdentityUser()    {    }    /// <summary>    /// Initializes a new instance of <see cref="T:Microsoft.AspNetCore.Identity.IdentityUser`1" />.    /// </summary>    /// <param name="userName">The user name.</param>    public IdentityUser(string userName)      : this()    {      this.UserName = userName;    }    /// <summary>Gets or sets the primary key for this user.</summary>    public virtual TKey Id { get; set; }    /// <summary>Gets or sets the user name for this user.</summary>    public virtual string UserName { get; set; }    /// <summary>Gets or sets the normalized user name for this user.</summary>    public virtual string NormalizedUserName { get; set; }    /// <summary>Gets or sets the email address for this user.</summary>    public virtual string Email { get; set; }    /// <summary>    /// Gets or sets the normalized email address for this user.    /// </summary>    public virtual string NormalizedEmail { get; set; }    /// <summary>    /// Gets or sets a flag indicating if a user has confirmed their email address.    /// </summary>    /// <value>True if the email address has been confirmed, otherwise false.</value>    public virtual bool EmailConfirmed { get; set; }    /// <summary>    /// Gets or sets a salted and hashed representation of the password for this user.    /// </summary>    public virtual string PasswordHash { get; set; }    /// <summary>    /// A random value that must change whenever a users credentials change (password changed, login removed)    /// </summary>    public virtual string SecurityStamp { get; set; }    /// <summary>    /// A random value that must change whenever a user is persisted to the store    /// </summary>    public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();    /// <summary>Gets or sets a telephone number for the user.</summary>    public virtual string PhoneNumber { get; set; }    /// <summary>    /// Gets or sets a flag indicating if a user has confirmed their telephone address.    /// </summary>    /// <value>True if the telephone number has been confirmed, otherwise false.</value>    public virtual bool PhoneNumberConfirmed { get; set; }    /// <summary>    /// Gets or sets a flag indicating if two factor authentication is enabled for this user.    /// </summary>    /// <value>True if 2fa is enabled, otherwise false.</value>    public virtual bool TwoFactorEnabled { get; set; }    /// <summary>    /// Gets or sets the date and time, in UTC, when any user lockout ends.    /// </summary>    /// <remarks>A value in the past means the user is not locked out.</remarks>    public virtual DateTimeOffset? LockoutEnd { get; set; }    /// <summary>    /// Gets or sets a flag indicating if the user could be locked out.    /// </summary>    /// <value>True if the user could be locked out, otherwise false.</value>    public virtual bool LockoutEnabled { get; set; }    /// <summary>    /// Gets or sets the number of failed login attempts for the current user.    /// </summary>    public virtual int AccessFailedCount { get; set; }    /// <summary>Returns the username for this user.</summary>    public override string ToString()    {      return this.UserName;    }  }}

This class has already defined some account attributes. If we think we need to add custom attributes, such as the user's address, we only need to add custom attributes to the class we inherit;

Create Database context:

The following code creates a data context to connect to the database:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;using Microsoft.EntityFrameworkCore;namespace DemoUser.Models{    public class AppIdentityDbContext :IdentityDbContext<AppUser>    {        public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options)            : base(options) { }    }}
Configure the database connection string:

To connect to the database, we need to configure a connection string. Modify the appsettings. json file as follows:

 

{  "Data": {    "AppStoreIdentity": {      "ConnectionString": "Server=192.168.0.4;Database=IdentityUsers;User ID =SA; Password=!@#"    }   }}

 

Next we need to configure the connection string to the database context in the startup class;

public void ConfigureServices(IServiceCollection services) {            services.AddDbContext<AppIdentityDbContext>(options =>                options.UseSqlServer(                    Configuration["Data:AppStoreIdentity:ConnectionString"]));            services.AddIdentity<AppUser, IdentityRole>()                .AddEntityFrameworkStores<AppIdentityDbContext>()                .AddDefaultTokenProviders();            services.AddMvc();        }
Create a database:

Next we need to use EFCore to generate a database:

Open the console, locate the current project, and enter:

Dotnet ef migrations add Initial
Then a migrations folder is generated, which contains the code for generating the database;
Then enter:
Dotnet ef database update
In this way, our database will generate
 

Here is my uploaded github repository address: https://github.com/bluetianx/AspnetCoreExample

Follow-up:

I will create an account management interface with addition, deletion, modification, and query

 

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.