zoukankan      html  css  js  c++  java
  • IdentityServer(14)- 通过EntityFramework Core持久化配置和操作数据

    本文用了EF,如果不适用EF的,请参考这篇文章,实现这些接口来自己定义存储等逻辑。http://www.cnblogs.com/stulzq/p/8144056.html

    IdentityServer具有良好的扩展性,其中一个可扩展点是用于IdentityServer所需数据的存储机制。 本快速入门介绍了如何配置IdentityServer以使用EntityFramework(EF)作为此数据的存储机制(而不是使用我们迄今为止使用的内存中实现)。

    IdentityServer4.EntityFramework组件

    有两种类型的数据需要持久化到数据库中。 首先是配置数据(资源和客户端),第二个是IdentityServer在使用时产生的操作数据(令牌,代码和用户的授权信息consents)。 这些存储采用接口进行建模,我们在IdentityServer4.EntityFramework Nuget包中提供这些接口的EF实现。

    IdentityServer项目通过添加对IdentityServer4.EntityFramework Nuget包的引用开始。

    使用SqlServer

    鉴于EF的灵活性,您可以使用任何EF支持的数据库。 对于这个快速入门,我们将使用Visual Studio附带的SqlServer的LocalDb版本。

    数据库Schema更改和使用EF迁移

    IdentityServer4.EntityFramework包包含从IdentityServer的模型映射的实体类。 随着IdentityServer的模型的改变,IdentityServer4.EntityFramework中的实体类也会改变。 当您使用IdentityServer4.EntityFramework并随着时间的推移升级时,您将负责自己的数据库Schema以及实体类更改所需的更改。 管理这些变化的一种方法是使用EF迁移,这个快速入门将显示如何完成。 如果迁移不是您的偏好,那么您可以以任何您认为合适的方式管理架构更改。

    为IdentityServer4.EntityFramework中的实体维护SqlServer的SQL脚本。 https://github.com/IdentityServer/IdentityServer4.EntityFramework/tree/dev/src/Host/Migrations/IdentityServer

    使用EF工具进行迁移

    关于EF迁移可以看我的这篇文章:http://www.cnblogs.com/stulzq/p/7717873.html

    我们需要手动更改项目的csproj文件来添加EF工具:

    然后在结束</ Project>元素之前添加下面的代码片段:

    <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    </ItemGroup>
    

    看起来像这样:

    保存并关闭文件。 为了测试你已经正确安装了这些工具,你可以在项目所在的目录下打开一个命令shell并运行dotnet ef。 它应该是这样的:

    配置store

    下一步是在Startup.cs中ConfigureServices方法中的AddInMemoryClients,AddInMemoryIdentityResources和AddInMemoryApiResources进行替换。 我们将用这个代码替换它们:

    const string connectionString = @"Data Source=(LocalDb)MSSQLLocalDB;database=IdentityServer4.Quickstart.EntityFramework-2.0.0;trusted_connection=yes;";
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
    
    // configure identity server with in-memory stores, keys, clients and scopes
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddTestUsers(Config.GetUsers())
        // this adds the config data from DB (clients, resources)
        .AddConfigurationStore(options =>
        {
            options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
        })
        // this adds the operational data from DB (codes, tokens, consents)
        .AddOperationalStore(options =>
        {
            options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
                    sql => sql.MigrationsAssembly(migrationsAssembly));
    
            // this enables automatic token cleanup. this is optional.
            options.EnableTokenCleanup = true;
            options.TokenCleanupInterval = 30;
        });
    

    您可能需要将这些命名空间添加到文件中:

    using Microsoft.EntityFrameworkCore;
    using System.Reflection;
    

    上面的代码是对一个连接字符串进行硬编码,如果你愿意,你可以随意更改。 此外,对AddConfigurationStoreAddOperationalStore的调用是注册EF支持的存储实现。

    传递给这些API的“builder”回调方法是EF的机制,允许您为这两个存储中的每一个配置用于DbContextDbContextOptionsBuilder。 这就是我们的DbContext类可以用你想要使用的数据库提供程序来配置。 在这种情况下,通过调用UseSqlServer,我们正在使用SqlServer。 你也可以知道,这是提供连接字符串的地方。

    UseSqlServer中的“options”回调函数是配置定义EF迁移的程序集的方法。 EF需要使用迁移来定义数据库的Schema。

    添加迁移

    要创建迁移,请在IdentityServer项目目录中打开命令提示符。 在命令提示符下运行这两个命令:

    dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
    dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
    

    执行情况应该如下:

    您现在应该在项目中看到一个〜/ Data / Migrations / IdentityServer文件夹。 这包含新创建的迁移的代码。

    初始化数据库

    现在我们已经添加了迁移,我们可以编写代码来从迁移中创建数据库。 我们还将使用我们在之前的快速入门中定义的内存配置数据对数据库进行种子处理。

    在Startup.cs中添加这个方法来帮助初始化数据库:

    private void InitializeDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
    
            var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
            context.Database.Migrate();
            if (!context.Clients.Any())
            {
                foreach (var client in Config.GetClients())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }
    
            if (!context.IdentityResources.Any())
            {
                foreach (var resource in Config.GetIdentityResources())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
    
            if (!context.ApiResources.Any())
            {
                foreach (var resource in Config.GetApiResources())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
    }
    

    然后我们可以从Configure方法调用它:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // this will do the initial DB population
        InitializeDatabase(app);
    
        // the rest of the code that was already here
        // ...
    }
    

    现在,如果运行IdentityServer项目,则应创建数据库并使用快速入门配置数据进行种子插入。 您应该能够使用SQL Server Management Studio或Visual Studio来连接和检查数据。

    运行程序

    您现在应该能够运行任何现有的客户端应用程序并登录,获取令牌并调用API - 全部基于数据库配置。

    本文代码:https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Quickstarts/7_EntityFrameworkStorage
    原文:https://identityserver4.readthedocs.io/en/latest/quickstarts/7_entity_framework.html

  • 相关阅读:
    国内10大前端团队网站
    可视化搭建前端工程
    Vue CLI环境变量和模式
    BetterScroll:可能是目前最好用的移动端滚动插件
    洛谷月赛
    CF438D The Child and Sequence
    P1447 [NOI2010]能量采集
    Cow Relays,过N条边的最短路
    Numerical Sequence(hard version),两次二分
    洛谷P3237 米特运输
  • 原文地址:https://www.cnblogs.com/stulzq/p/8120518.html
Copyright © 2011-2022 走看看