如何在IdentityServer4上实现缓存?

How to implement caching on IdentityServer4?

如何在IdSrv4中为ClientStore实现缓存?我已经在 AddClientStoreCache 查看文档 但这对我没有帮助... 在我的 ConfigureServices 方法中,我按如下方式配置 IdSrv:

services.AddIdentityServer(options =>
        {
            options.IssuerUri = "http://idp.address.jus.br/";
            options.Caching.ClientStoreExpiration = TimeSpan.FromHours(1);
        })
        .AddSigningCredential(cert)
        .AddClientStoreCache<ClientStore>();

...在我的 ClientStore 实现中,我没有任何关于缓存的信息...我应该检查信息是否在缓存中 FindClientByIdAsync 在某种程度上?或者它是在后台为我完成的?

我只在 IdentityServer4.Postgresql 找到了一个样本,但我无法在我的自定义 Store 类...[= 上成功复制它13=]

如果您正在寻找 CachingClientStore.cs 的示例实现,您可以查看默认实现(身份服务器执行此操作的方式)here

public async Task<Client> FindClientByIdAsync(string clientId)
{
     var client = await _cache.GetAsync(clientId,
     _options.Caching.ClientStoreExpiration,
     () => _inner.FindClientByIdAsync(clientId),
     _logger);

     return client;
}

他们让您选择如何实现缓存算法。您可以将 ClientStore 缓存在内存数据库中,例如 Redis。 IdentityServer4 的好处是您可以根据需要实现接口。

AddConfigurationStoreCache() 通过 https://github.com/IdentityServer/IdentityServer4/blob/master/src/EntityFramework/host/Startup.cs#L47

在startup.cs中我只写:

     //Load user /password in runtime
            services.AddTransient<IResourceOwnerPasswordValidator, DBResourceOwnerPasswordValidator>();

///verify by clientid & client secrect in mssql 

services.AddTransient<IClientStore, DbClientStore>(); 

在DbClientStore.cs中:

public class DbClientStore : IClientStore
    {
        IDNHClientsServices clientsService;
        protected IStaticCacheManager cacheManager ;
        public DbClientStore(IDNHClientsServices repository, IStaticCacheManager staticCacheManager)
        {
            clientsService = repository;
            cacheManager = staticCacheManager;
        }
        /// <summary>
        /// Dùng để get client secrect trong db trung quá trình runtime
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public Task<Client> FindClientByIdAsync(string clientId)
        {
            
            ClientsResponse client = cacheManager.Get(string.Format("clientkey.{0}", clientId), () => clientsService.GetClientInfo(clientId).Result);
            if (client == null)
            {
                return Task.FromResult<Client>(null);
            }
           
            ICollection<string> type = null;
            switch (client.AllowedGrantTypes)
            {
                case GrantType.ResourceOwnerPassword:
                    type = GrantTypes.ResourceOwnerPassword;
                    break;
                case GrantType.ClientCredentials:
                    type = GrantTypes.ClientCredentials;
                    break;
                default:
                    type = GrantTypes.ResourceOwnerPassword;
                    break;
            }

            return Task.FromResult(new Client()
            {
                ClientId = client.clientId,
                AllowedGrantTypes = type,
                AllowedScopes = client.AllowedScopes,
                ClientSecrets = client.ClientSecrets
            });
        }
    }

public class ClientsResponse 
{
    public int Id { get; set; }
    public string clientId { get; set; }
    public string RedirectUris { get; set; }
    public string AllowedGrantTypes { get; set; }
    public bool Enable { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? UpdateDate { get; set; }
    public ICollection<string> AllowedScopes { get; set; }
    public ICollection<Secret> ClientSecrets { get; set; }
}

我知道这个话题有点老,但我找到了我的解决方案,可能会对某些人有所帮助。所以你只需要在startup.cs

中添加如下代码
using IdentityServer4.EntityFramework.Services;
using IdentityServer4.EntityFramework.Stores;

public void ConfigureServices(IServiceCollection services)
{
   services
   .AddIdentityServer(options =>
   {
      options.Caching.ClientStoreExpiration = TimeSpan.FromMinutes(10);
      options.Caching.ResourceStoreExpiration = TimeSpan.FromMinutes(10);
      options.Caching.CorsExpiration = TimeSpan.FromMinutes(10);
      //other options
   })
   .AddInMemoryCaching()
   .AddClientStoreCache<ClientStore>()
   .AddCorsPolicyCache<CorsPolicyService>()
   .AddConfigurationStoreCache()
   .AddResourceStoreCache<ResourceStore>()
   //other things

Source