From 30c8599f51656afa350c882658eccf3257ff2bb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B2=88=E6=98=9F=E7=B9=81?= Date: Thu, 20 Jun 2024 21:02:52 +0800 Subject: [PATCH] fix: authentication regression --- src/Cnblogs.DashScope.Core/DashScopeClient.cs | 5 ++++- .../DashScopeClientTests.cs | 18 +++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Cnblogs.DashScope.Core/DashScopeClient.cs b/src/Cnblogs.DashScope.Core/DashScopeClient.cs index 0c970b3..26f716f 100644 --- a/src/Cnblogs.DashScope.Core/DashScopeClient.cs +++ b/src/Cnblogs.DashScope.Core/DashScopeClient.cs @@ -1,4 +1,5 @@ -using Cnblogs.DashScope.Core.Internals; +using System.Net.Http.Headers; +using Cnblogs.DashScope.Core.Internals; namespace Cnblogs.DashScope.Core; @@ -33,6 +34,8 @@ private static HttpClient GetConfiguredClient(string apiKey, TimeSpan? timeout) BaseAddress = new Uri(DashScopeDefaults.DashScopeApiBaseAddress), Timeout = timeout ?? TimeSpan.FromMinutes(2) }; + + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); ClientPools.Add(GetCacheKey(), client); } diff --git a/test/Cnblogs.DashScope.Sdk.UnitTests/DashScopeClientTests.cs b/test/Cnblogs.DashScope.Sdk.UnitTests/DashScopeClientTests.cs index 54d05be..be60571 100644 --- a/test/Cnblogs.DashScope.Sdk.UnitTests/DashScopeClientTests.cs +++ b/test/Cnblogs.DashScope.Sdk.UnitTests/DashScopeClientTests.cs @@ -1,4 +1,5 @@ -using System.Reflection; +using System.Net.Http.Headers; +using System.Reflection; using Cnblogs.DashScope.Core; using FluentAssertions; @@ -59,6 +60,21 @@ public void DashScopeClient_Constructor_CacheableParams( value.Should().Be(value2); } + [Fact] + public void DashScopeClient_Constructor_WithApiKeyHeader() + { + // Arrange + const string apiKey = "key"; + var client = new DashScopeClient(apiKey); + + // Act + var value = HttpClientAccessor.GetValue(client) as HttpClient; + + // Assert + value?.DefaultRequestHeaders.Authorization?.Should() + .BeEquivalentTo(new AuthenticationHeaderValue("Bearer", apiKey)); + } + public static TheoryData ParamsShouldNotCache => new() {