/// <summary> /// 添加一个消息处理器,通过此消息处理器会在请求过程中,自动从认证服务获取令牌并添加到请求头中 /// 该处理器通过<seealso cref="IClientCertificateProvider"/>获取对应客户端的认证令牌 /// </summary> /// <param name="builder">HttpClient构建器</param> /// <param name="clientId">认证客户端Id</param> /// <returns></returns> public static IHttpClientBuilder AddTokenMessageHandler(this IHttpClientBuilder builder, string clientId) { builder.AddHttpMessageHandler((sp) => { IClientCertificateProvider provider = sp.GetRequiredService <IClientCertificateProvider>(); ClientCertificateManager cm = provider.GetClientCertificateManager(clientId); return(new GetClientTokenMessageHandler(cm)); }); return(builder); }
public void DistributedCache_Test() { IServiceCollection sc = new ServiceCollection() .AddLogging() .AddHttpClient() .AddDistributedMemoryCache(); var sp = sc.BuildServiceProvider(); ClientCertificateInfo ci = new ClientCertificateInfo() { ClientID = "1", AuthUrl = "1", ClientSecret = "1" }; MockTokenProcessor processor = new MockTokenProcessor(); CheckResponseProcessor checker = CheckResponseProcessor.NormalChecker; DistributedTokenCacheManager cacheManager = new DistributedTokenCacheManager( sp.GetRequiredService <IDistributedCache>(), ci.ClientID); ClientCertificateManager ccm = new ClientCertificateManager( ci, processor, SetTokenProcessor.Bearer, checker, cacheManager, sp.GetRequiredService <ILogger <ClientCertificateManager> >(), sp.GetRequiredService <IHttpClientFactory>()); List <Task> taskList = new List <Task>(); for (int i = 0; i < 10; i++) { taskList.Add(Task.Run(async() => { await ccm.GetAccessToken(); })); } Task.WaitAll(taskList.ToArray()); Assert.Equal(1, processor.exeCount); }