IdentityServer4.EntityFramework 使用教程
项目介绍
IdentityServer4.EntityFramework 是一个用于 IdentityServer4 的 EntityFramework 持久层。它提供了使用 Entity Framework Core 来存储 IdentityServer4 的配置和操作数据的能力。这个项目允许你在多个 IdentityServer 实例之间共享数据,并且支持使用 Entity Framework Core 兼容的关系数据库。
项目快速启动
安装依赖
首先,你需要安装 IdentityServer4.EntityFramework 和 Entity Framework Core SQL Server 的 NuGet 包:
dotnet add package IdentityServer4.EntityFramework
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
配置 DbContext
在你的 IdentityServer 项目中,配置 ConfigurationDbContext
和 PersistedGrantDbContext
:
using Microsoft.EntityFrameworkCore;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Options;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var connectionString = "your_connection_string";
var migrationsAssembly = typeof(Startup).Assembly.GetName().Name;
services.AddIdentityServer()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
});
}
}
添加迁移并更新数据库
使用 Entity Framework Core 工具添加迁移并更新数据库:
dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
dotnet ef database update
应用案例和最佳实践
应用案例
IdentityServer4.EntityFramework 可以用于任何需要集中管理 IdentityServer4 配置和操作数据的应用场景。例如,一个多租户应用程序可以使用这个库来为每个租户维护独立的配置和操作数据。
最佳实践
- 使用迁移:始终使用 Entity Framework Core 迁移来管理数据库 schema 的变化。
- 分离配置和操作数据:使用
ConfigurationDbContext
和PersistedGrantDbContext
分别管理配置数据和操作数据,这样可以更好地控制数据的生命周期和清理策略。 - 定期清理操作数据:操作数据(如授权码和刷新令牌)应定期清理,以避免数据库膨胀。
典型生态项目
IdentityServer4.EntityFramework 是 IdentityServer4 生态系统中的一个重要组成部分。它与以下项目紧密集成:
- IdentityServer4:核心的 OpenID Connect 和 OAuth 2.0 框架。
- ASP.NET Core Identity:用于用户管理和认证。
- Entity Framework Core:用于数据持久化。
这些项目共同构成了一个完整的身份和访问管理解决方案,适用于各种现代应用程序和微服务架构。