一、简介
1、概况
ASP.NET Core Identity是一个成员身份系统,可将用户注册和登录功能添加到 ASP.NET Core Web UI。 成员身份系统处理身份验证和授权问题。 身份验证涉及你的身份。 授权涉及允许你进行的操作。 因此,身份验证是授权的先决条件。 ASP .Net Core Identity内置了一组认证功能,用于简单的Web应用的认证和授权。
ASP.NET Core Identity:
- 一个 API,它支持用户界面 (UI) 登录功能。
 - 管理用户、密码、配置文件数据、角色、声明、令牌、电子邮件确认等等。
 
Identity ASP.NET Core与Microsoft 标识平台无关。 ASP.NET Core Identity 将用户界面 (UI) 登录功能添加到 ASP.NET Core Web 应用。 若要保护 Web API 和 SPA,请使用以下项之一:
- Azure Active Directory
 - Azure Active Directory B2C (Azure AD B2C)
 - Identity Server4
 
IdentityServer4 是适用于 ASP.NET Core 的 OpenID Connect 和 OAuth 2.0 框架。 IdentityServer4 支持以下安全功能:
- 身份验证即服务 (AaaS)
 - 跨多个应用程序类型的单一登录/注销 (SSO)
 - API 的访问控制
 - Federation Gateway
 
2、结构
Identity 通常使用 SQL Server 数据库进行配置,以存储用户名、密码和配置文件数据。 或者,可使用其他持久性存储,例如 Azure 表存储。Identity的层次结构如下:

在上图中:
- ASP.NET Core Razor Pages 应用表示将在本模块中向其添加标识支持的 Web UI。
 - Identity Manager 层包含 
Microsoft.AspNetCore.Identity命名空间中使用的类。 本模块中显式使用的此类的示例是SignInManager<TUser>和UserManager<TUser>。 - EF Core 标识存储区层包含 
Microsoft.AspNetCore.Identity.EntityFrameworkCore命名空间中的类。 本模块中隐式使用的此类的示例是UserStore<TUser>。 - 数据库提供程序是一种特定于数据库的库,它接受来自 EF Core 提供程序(未示出)的 SQL 并执行它。
 
EF Core 使用一项称为迁移的功能来增量更新数据库架构,使其与应用的数据模型保持同步。 应用初始 EF Core 迁移后,将创建支持的数据库表。 下图描述了支持Indentity的表的架构:

3、Identity实体模型和实体间关系
Identity 模型
实体类型
Identity 模型包含以下实体类型。
| 实体类型 | 说明 | 
|---|---|
User | 表示用户。 | 
Role | 表示一个角色。 | 
UserClaim | 表示用户拥有的声明。 | 
UserToken | 表示用户的身份验证令牌。 | 
UserLogin | 将用户与登录名相关联。 | 
RoleClaim | 表示向角色中所有用户授予的声明。 | 
UserRole | 关联用户和角色的联接实体。 | 
实体类型关系
实体类型通过以下方式相互相关:
- 每个 
User可以有多个UserClaims。 - 每个 
User可以有多个UserLogins。 - 每个 
User可以有多个UserTokens。 - 每个 
Role可以有多个关联的RoleClaims。 - 每个 
User可以有多个关联的Roles,并且每个Role可以与多个Users关联。 这是一种多对多关系,需要数据库中的联接表。 联接表由UserRole实体表示。 
二、试用
1、使用基架添加Indentity认证结构
安装基架工具
dotnet tool install dotnet-aspnet-codegenerator --version 6.0.2 --global 
向项目添加以下NuGet包
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 6.0.2
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 6.0.3
dotnet add package Microsoft.AspNetCore.Identity.UI --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.3
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.3 
使用基架命令向项目添加默认标识组件。 在终端中运行以下命令:
dotnet aspnet-codegenerator identity --useDefaultUI --dbContext ProjectDbContext 
项目下,新增目录结构
Areas
  └─Identity
     ├─Data
     └─Pages
         └─Account
             └─Manage 
查看基架向项目添加的文件列表
$> dotnet aspnet-codegenerator identity --listFiles
Building project ...
Finding the generator 'identity'...
Running the generator 'identity'...
File List:
Account._StatusMessage
Account.AccessDenied
Account.ConfirmEmail
Account.ConfirmEmailChange
Account.ExternalLogin
Account.ForgotPassword
Account.ForgotPasswordConfirmation
Account.Lockout
Account.Login
Account.LoginWith2fa
Account.LoginWithRecoveryCode
Account.Logout
Account.Manage._Layout
Account.Manage._ManageNav
Account.Manage._StatusMessage
Account.Manage.ChangePassword
Account.Manage.DeletePersonalData
Account.Manage.Disable2fa
Account.Manage.DownloadPersonalData
Account.Manage.Email
Account.Manage.EnableAuthenticator
Account.Manage.ExternalLogins
Account.Manage.GenerateRecoveryCodes
Account.Manage.Index
Account.Manage.PersonalData
Account.Manage.ResetAuthenticator
Account.Manage.SetPassword
Account.Manage.ShowRecoveryCodes
Account.Manage.TwoFactorAuthentication
Account.Register
Account.RegisterConfirmation
Account.ResendEmailConfirmation
Account.ResetPassword
Account.ResetPasswordConfirmation
RunTime 00:00:08.09 
文件夹和所包含的文件
- Data/ 
  
- RazorPagesPizzaUser.cs
 
 - Pages/ 
  
- _ViewImports.cshtml
 - Account/ 
    
- _ViewImports.cshtml
 - ConfirmEmail.cshtml
 - ConfirmEmail.cshtml.cs
 - Register.cshtml
 - Register.cshtml.cs
 - Manage/ 
      
- _ManageNav.cshtml
 - _ViewImports.cshtml
 - EnableAuthenticator.cshtml
 - EnableAuthenticator.cshtml.cs
 - Index.cshtml
 - Index.cshtml.cs
 - ManageNavPages.cs
 
 
 
 
在配置完数据库上下文后,用EF Core更新数据库后,便可运行。
dotnet tool install dotnet-ef --version 6.0.3 --global
dotnet ef migrations add CreateIdentitySchema
dotnet ef database update 
2、自定义认证
创建新用户类继承自IdentityUser(已在内部定义),并可添加自定义的属性和方法
public class RazorPagesPizzaUser : IdentityUser
{
    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; } = string.Empty;
    [Required]
    [MaxLength(100)]
    public string LastName { get; set; } = string.Empty;
    public string BirthDay {get;set;} = string.Empty;
} 
根据自定义用户属性更新数据库
dotnet ef migrations add UpdateUser
dotnet ef database update 
查看数据结构已添加新属性
 
再同步更新,Register、Index等相关页面中的控件、验证信息,便可以运行
3、启用认证
在需要验证的页面中添加【Authorise】便可以启用验证了
[Authorize]
public class PizzaModel : PageModel 
 
尝试注册 一个新用户

Register后服务端自然生成确认URL,在有外网smtp服务器的情况下,可以自动发至注册邮箱。
Email Confirmation Message
--------------------------
TO: abcd@shanghai.com
SUBJECT: Confirm your email
CONTENTS: Please confirm your account by visiting the following URL:
https://localhost:7192/Identity/Account/ConfirmEmail?userId=fc053309-f4e3-455c-9ff4-08b1842a9fc1&code=Q2ZESjhGb3puQnVsQTBGSGxadFhSUmdBZWQrdG9Tb0pKcU1CeU8vZHdLYm9ycnRYaE1hdjJZeWxoM3BJSzJoVk84TEx4VkgxME9wN3RqWldPQ0gxN1BjVjF4dGxwdkhnOGJMZ0FlWW8rZXhTYjJlSjlvaERLTXQ2eGFQb29oSGdPbWVud2hLUXRrZSs5NXpoeGZwZHdDSm5QV1FYeDdIYUI3RTl1ME9yaURiQjc4Y0YvZWRIa0xUeU1YNFYwMmpvUU9kQUQ3L3VmRy9obGJtTkNWVE10SXU1dVBQd2g4V2Y3aHhHdHBqdG8vWXNpSGJ0MFVHbHgvNVI1WmxCYmtvNlhEUE1Kdz09&returnUrl=%2F 
确认后登录,便可访问所认证页面
 
登录后就可以访问List页面

完成了,用户认证、授权的最简过程。
三、参考文章
1、简介 - Training | Microsoft Learn
2、ASP.NET Core 中的 Identity 模型自定义 | Microsoft Learn
3、ASP.NET Core 上的 Identity 简介 | Microsoft Learn


















