IdentityServer 4,为CRUD客户端创建面板

use*_*055 3 c# entity-framework-core asp.net-core identityserver4

目前,我已将Identityserver4配置为独立项目+ My WebAPI并存储在IdentityServer的DB凭据中.

现在我有问题如何在IdentityServer中创建CRUD(在我的前端API中)(我希望从我的API添加客户端到IdentityServer)

如何制作房产?

Kir*_*kin 10

来自IdentityServer4.EntityFrameworkIdentityServer4.EntityFramework.Storage,您可以访问IConfigurationDbContext(一旦您在ConfigureServices使用中添加了所需的服务,例如AddConfigurationStore).因为它是作为依赖注入系统的一部分注册的,所以您可以在其中一个控制器中依赖它.例如:

public class ClientsController : ControllerBase
{
    private readonly IConfigurationDbContext _configurationDbContext;

    public ClientsController(IConfigurationDbContext configurationDbContext)
    {
        _configurationDbContext = configurationDbContext;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

IConfigurationDbContext是标准的抽象DbContext,具有以下DbSet<T>属性:

  • Clients
  • IdentityResources
  • ApiResources

它还包括SaveChangesSaveChangesAsync- 一个人可能期望的一切DbContext.由于所有这些,您可以像任何其他Entity Framework Core驱动的数据库一样CRUD这些实体.

最后要注意的是,有Models(in IdentityServer4.Storage)和Entities(in IdentityServer4.EntityFramework.Storage).还有一些用于在这些之间进行映射的扩展方法(例如ClientMappers.ToEntity).

鉴于所有这些,您可以创建一个Model控制器内部(或者可能在某个地方封装比直接更好).这是创建新的基本示例Client:

var clientModel = new Client
{
    ClientId = "",
    ClientName = "",
    // ...
};

_configurationDbContext.Clients.Add(clientModel.ToEntity());

await _configurationDbContext.SaveChangesAsync();
Run Code Online (Sandbox Code Playgroud)

Client这里的类来自,IdentityServer4.Models然后转换为Entity使用ToEntity我在上面提到的扩展方法.使用a Model并转换为a Entity比尝试Entity直接操作更简单- 如果您感兴趣,可以在此处查看映射.

这对于ApiResources,IdentityResources等等有同样的作用.如果你想了解更多关于这些的信息,请使用我提供的源代码链接,但是我在这里提供的信息应该包括在内.

要在API项目中使用IdentityServer4IdentityServer4.EntityFramework,您只需将两个引用添加到API项目中即可.之后,您可以以相同的方式配置DI(使用AddIdentityServerin ConfigureServices),但不需要添加中间件(使用UseIdentityServerin Configure).您甚至可以使用AddIdentityServer().AddConfigurationStore(...)设置相关服务,因为您不需要签名密钥等.