From 9875f0ff4dbc8cf2b5af3b60ae9b8967b1e44477 Mon Sep 17 00:00:00 2001 From: hello Date: Fri, 1 Mar 2024 11:33:07 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=95=B0=E6=8D=AE=E5=86=85?= =?UTF-8?q?=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/efcore-postgresql-provider.md | 148 ++++++++++++++++++ notes/helloshop/identity-api-endpoints.md | 101 ++++++++++++ notes/helloshop/identity.md | 106 ------------- notes/helloshop/openapi.md | 29 ++++ 4 files changed, 278 insertions(+), 106 deletions(-) create mode 100644 notes/helloshop/efcore-postgresql-provider.md create mode 100644 notes/helloshop/identity-api-endpoints.md delete mode 100644 notes/helloshop/identity.md create mode 100644 notes/helloshop/openapi.md diff --git a/notes/helloshop/efcore-postgresql-provider.md b/notes/helloshop/efcore-postgresql-provider.md new file mode 100644 index 0000000..23960ec --- /dev/null +++ b/notes/helloshop/efcore-postgresql-provider.md @@ -0,0 +1,148 @@ +# 使用 PostgreSQL 数据库存储数据 + +## 在 Docker 中 启动 PostgreSQL 数据库 + +https://www.postgresql.org + +```shell +docker pull postgres +docker run --name postgres -e POSTGRES_PASSWORD=postgres -e TZ=Asia/Shanghai -d -p 5432:5432 postgres +``` + +## 使用 PgAdmin 连接 PostgreSQL 数据库 + +https://www.pgadmin.org + +```shell +SHOW timezone; +``` + +## EfCore 使用 PostgreSQL 数据库 + +```shell +dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL +``` + +## 定义实体类型 + +```csharp +public class User +{ + public int Id { get; set; } + public string UserName { get; set; } + public string PasswordHash { get; set; } + public DateTimeOffset CreationTime { get; set; } = DateTimeOffset.UtcNow; +} +``` + +## 配置实体类型 + +```csharp +public class UserEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Users"); + builder.HasKey(x => x.Id); + builder.Property(x => x.UserName).IsRequired().HasMaxLength(50); + builder.Property(x => x.PasswordHash).IsRequired().HasMaxLength(50); + builder.Property(x => x.CreationTime); + } +} +``` + +## 创建 DbContext 上下文 + +```csharp +public class IdentityServiceDbContext : DbContext +{ + public IdentityServiceDbContext(DbContextOptions options) : base(options) + { + } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); + + AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); + AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); + } +} +``` + +## 数据库连接字符串 + +```json +{ + "ConnectionStrings": { + "IdentityDatabase": "Host=localhost;Port=5432;Database=IdentityService;Username=postgres;Password=postgres" + } +} +``` + +## 注册数据库上下文 + +```csharp +builder.Services.AddDbContext(options => +{ + options.UseNpgsql(builder.Configuration.GetConnectionString("IdentityDatabase")); +}); +``` + +## 迁移数据库 + +```shell +dotnet tool install --global dotnet-ef +dotnet add package Microsoft.EntityFrameworkCore.Design +``` + +```shell +dotnet ef migrations add InitialCreate --output-dir EntityFrameworks/Migrations +dotnet ef database update +``` + +## PostgreSQL 数据库命名约定 + +https://github.com/efcore/EFCore.NamingConventions + +## 删除数据库和迁移 + +```shell +dotnet ef database drop --force +dotnet ef migrations remove +``` + +## 使用脚本迁移 + +```shell +dotnet ef migrations script +``` + +## EF Core 列迁移排序 + +默认情况下,在使用迁移创建表时,EF Core 首先为主键列排序,然后为实体类型和从属类型的属性排序,最后为基类型中的属性排序。 但是,你可以指定不同的列顺序: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + modelBuilder.Entity() + .Property(b => b.Url) + .HasColumnOrder(2); + + modelBuilder.Entity() + .Property(b => b.Rating) + .HasColumnOrder(3); +} +``` + +## PostgreSQL 驱动时间自动转换配置 + + +```csharp + +AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); +AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); + +``` \ No newline at end of file diff --git a/notes/helloshop/identity-api-endpoints.md b/notes/helloshop/identity-api-endpoints.md new file mode 100644 index 0000000..54a3438 --- /dev/null +++ b/notes/helloshop/identity-api-endpoints.md @@ -0,0 +1,101 @@ +# 身份认证系统 + +## ASP.NET Core Identity 体系结构 + +ASP.NET Core Identity 是一个成熟的身份认证系统,它提供了用户管理、角色管理、声明管理、密码管理、登录管理、外部登录管理、双重身份认证、电子邮件确认、电话号码确认、安全令牌管理、用户锁定、用户解锁、用户注销、用户删除、用户恢复等功能。 + +## Identity 体系结构说明 + +|实体类型|说明 | +|-----------|--------------------------------------------------| +|`User` |表示用户。 | +|`Role` |表示角色。 | +|`UserClaim`|表示用户拥有的声明。 | +|`UserToken`|表示用户的身份验证令牌。 | +|`UserLogin`|将用户与登录名相关联。 | +|`RoleClaim`|表示向角色内的所有用户授予的声明。| +|`UserRole` |关联用户和角色的联接实体。 | + + +## 使用 EfCore 存储 Identity 数据 + +### 定义实体类型 + +```csharp +public class User : IdentityUser +{ + public DateTimeOffset CreationTime { get; set; } = DateTimeOffset.UtcNow; +} + +public class Role : IdentityRole +{ + public DateTimeOffset CreationTime { get; set; } = DateTimeOffset.UtcNow; +} +``` + +### 配置实体类型 + +```csharp +public class UserEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Users"); + builder.HasKey(x => x.Id); + builder.Property(x => x.CreationTime); + } +} +``` + +### 复用 Identity 数据库上下文 + +```csharp +dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore +``` + +```csharp +public class IdentityServiceDbContext(DbContextOptions options) : IdentityDbContext(options => { + options.Password.RequireDigit = false; + options.Password.RequireLowercase = false; + options.Password.RequireUppercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequiredLength = 5; + options.SignIn.RequireConfirmedAccount = false; +}).AddEntityFrameworkStores(); + +app.MapGroup("identity").MapIdentityApi(); +``` + +## 操作 Identity 数据 + +UserManager、RoleManager、SignInManager、PasswordValidator 等服务都可以用来操作 Identity 数据,没有特殊情况不建议使用 DbContext 直接操作 Identity 数据。 + +## 使用终结点资源管理器 + +可以在 Visual Studio 2022 以上版本中,点击 "视图" > "其他窗口" > "终结点资源管理器" 来打开该功能。 + +## 测试 API 接口 + +CURL 命令行工具、Edge 网络控制台、OpenApi、HTTP 文件、Postman、Insomnia、Visual Studio Code REST Client 插件等工具都可以用来测试 API 接口。 + + +## 参考资料 + +https://learn.microsoft.com/zh-cn/aspnet/core/security/authentication/identity-api-authorization + +https://www.cnblogs.com/dongfo/p/17808249.html \ No newline at end of file diff --git a/notes/helloshop/identity.md b/notes/helloshop/identity.md deleted file mode 100644 index 3b431ee..0000000 --- a/notes/helloshop/identity.md +++ /dev/null @@ -1,106 +0,0 @@ -# 身份认证系统 - -## 在 Docker 中 启动 PostgreSQL 数据库 - -https://www.postgresql.org - -```shell -docker pull postgres -docker run --name postgres -e POSTGRES_PASSWORD=postgres -e TZ=Asia/Shanghai -d -p 5432:5432 postgres -``` - -## 使用 PgAdmin 连接 PostgreSQL 数据库 - -https://www.pgadmin.org - -```shell -SHOW timezone; -``` - -## EfCore 使用 PostgreSQL 数据库 - -```shell -dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL -``` - -## 使用 EfCore 存储 Identity - -```shell -dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore -``` - -## 迁移数据库 - -```shell -dotnet tool install --global dotnet-ef -dotnet add package Microsoft.EntityFrameworkCore.Design -``` - -```shell -dotnet ef migrations add InitialCreate --output-dir EntityFrameworks/Migrations -dotnet ef database update -``` - -## PostgreSQL 数据库命名约定 - -https://github.com/efcore/EFCore.NamingConventions - -## 删除数据库和迁移 - -```shell -dotnet ef database drop --force -dotnet ef migrations remove -``` - -## 使用脚本迁移 - -```shell -dotnet ef migrations script -``` - -## EF Core 列迁移排序 - -默认情况下,在使用迁移创建表时,EF Core 首先为主键列排序,然后为实体类型和从属类型的属性排序,最后为基类型中的属性排序。 但是,你可以指定不同的列顺序: - -```csharp -protected override void OnModelCreating(ModelBuilder modelBuilder) -{ - modelBuilder.Entity() - .Property(b => b.Url) - .HasColumnOrder(2); - - modelBuilder.Entity() - .Property(b => b.Rating) - .HasColumnOrder(3); -} -``` - -## PostgreSQL 数据库驱动时间自动转换 - - -```csharp - -AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); -AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); - -``` - -## Identity 体系结构说明 - -|实体类型|说明 | -|-----------|-------------------------------------------------------------| -|`User` |表示用户。 | -|`Role` |表示角色。 | -|`UserClaim`|表示用户拥有的声明。 | -|`UserToken`|表示用户的身份验证令牌。 | -|`UserLogin`|将用户与登录名相关联。 | -|`RoleClaim`|表示向角色内的所有用户授予的声明。| -|`UserRole` |关联用户和角色的联接实体。 | - - -- 每个 `User` 可以有多个 `UserClaims` -- 每个 `User` 可以有多个 `UserLogins`。 -- 每个 `User` 可以有多个 `UserTokens`。 -- 每个 `Role` 可以有多个关联的 `RoleClaims`。 -- 每个 `User` 可以有多个关联的 `Roles` -- 每个 `Role` 可以与多个 `Users`关联。 一个多对多关系,联接表由 `UserRole` 表示。 diff --git a/notes/helloshop/openapi.md b/notes/helloshop/openapi.md new file mode 100644 index 0000000..5c75118 --- /dev/null +++ b/notes/helloshop/openapi.md @@ -0,0 +1,29 @@ +# 使用 OpenAPI 规范生成 API 文档 + +Swagger 是一个与语言无关的规范,用于描述 REST API。 它使计算机和用户无需直接访问源代码即可了解 REST API 的功能,Swagger 项目已于捐赠给 OpenAPI 计划,自此它被称为 OpenAPI 规范。 + +Swashbuckle 是一个用于 .NET Core 的开源项目,它是 OpenAPI 工具的集合,用于生成 OpenAPI 规范的文档。 它可以自动生成 API 文档,包括 API 的描述、请求和响应的格式、参数的描述等。 + +## 安装 Swashbuckle.AspNetCore + +在 .NET Core 项目中,可以通过 NuGet 安装 Swashbuckle.AspNetCore 包。 + +```shell +dotnet add package Swashbuckle.AspNetCore +``` + +## 配置 Swashbuckle + +在 Startup.cs 文件中,可以通过以下方式配置 Swagger: + +```csharp +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} +``` +