IdentityServer 3 - 使用数据库中的客户端和范围

IdentityServer 3 - Using Client and Scope from DB

我是 IdentityServer 3 的新手,示例和教程使用的是 InMemory 用户、客户端和范围,但我需要这些来自 DB。所以我做了:

Startup.cs

public void Configuration(IAppBuilder app)
{
    // Allow all origins
    app.UseCors(CorsOptions.AllowAll);

    var factory = new IdentityServerServiceFactory();

    var userService = new UserService();
    var clientStore = new ClientStore();
    var scopeStore = new ScopeStore();
    var corsService = new CorsService();

    factory.UserService = new Registration<IUserService>(resolver => userService);
    factory.ClientStore = new Registration<IClientStore>(resolver => clientStore);
    factory.ScopeStore = new Registration<IScopeStore>(resolver => scopeStore);
    factory.CorsPolicyService = new Registration<ICorsPolicyService>(resolver => corsService);



    var options = new IdentityServerOptions
    {
        SiteName = "Embedded IdentityServer",
        SigningCertificate = LoadCertificate(),
        Factory = factory
    };

    app.UseIdentityServer(options);
}

但是在 ClientStore 和 ScopeStore 中,我必须将我的 Client/Scope 数据库模型映射到 IdentityServer3.Core.Models Client/Scope。像这样:

ClientStore.cs

public Task<Client> FindClientByIdAsync(string clientId)
{
    var clientFromDb = _db.Clients.SingleOrDefault(x => x.ClientId == clientId);
    var client = new Client
    {
        ClientName = clientFromDb.ClientName,
        ClientId = clientFromDb.ClientId,
        AccessTokenType = clientFromDb.AccessTokenType,
        Enabled = clientFromDb.Enabled,
        Flow = clientFromDb.Flow,
        RedirectUris = clientFromDb.RedirectUris.Select(x => x.Uri).ToList(),
        PostLogoutRedirectUris = clientFromDb.PostLogoutRedirectUris.Select(x => x.Uri).ToList(),
        AllowedCorsOrigins = clientFromDb.AllowedCorsOrigins.Select(x => x.Origin).ToList(),
        AllowedScopes = clientFromDb.AllowedScopes.Select(x => x.Scope).ToList(),
        AllowAccessToAllScopes = clientFromDb.AllowAccessToAllScopes,
        AccessTokenLifetime = clientFromDb.AccessTokenLifetime
    };

    return Task.FromResult(client);
}

知道我的数据库模型只是这些 IdentityServer3.Core.Models 的副本,有没有更好的方法来做到这一点?

factory.UserService = new Registration<IUserService>(resolver => userService);
factory.ClientStore = new Registration<IClientStore>(resolver => clientStore);
factory.ScopeStore = new Registration<IScopeStore>(resolver => scopeStore);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(resolver => corsService);

此样式将这些服务注册为单例。不知道是不是你想要的

如果每次使用都需要一个新实例,请使用:

factory.UserService = new Registration<IUserService, YourUserService>();

您是否尝试过使用 AutoMapper >> https://automapper.org/