获取Azure AD访问令牌以从本地应用程序调用Azure OpenAI资源的端点

dfddblmv  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(124)

我必须从内部部署应用程序的C#代码调用Azure OpenAI资源的ChatCompletions端点。
我有以下代码。我将在I register my application with Azure Active Directory之后获得客户端ID和客户端密钥。
如果我的应用程序是内部部署的,还没有迁移到Azure,这是否可行?

using Microsoft.Identity.Client;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AzureAdAccessToken
{
    public class AzureADHelper
    {
        private const string ClientId = "your_client_id";
        private const string TenantId = "your_azure_ad_tenant_id";
        private const string ClientSecret = "your_client_secret";
        private const string Scope = "https://cognitiveservices.azure.com/.default";
        private const string EndpointUrl = "https://your_azure_openai_endpoint_url";
        public static async Task<string> GetAccessToken()
        { 
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                .Create(ClientId)
                .WithClientSecret(ClientSecret)
                .WithAuthority($"https://login.microsoftonline.com/{TenantId}")
                .Build(); 
            
            string[] scopes = new string[] { Scope }; 
            
            AuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync(); 
            
            return result.AccessToken; 
        
        }
        public static async Task<string> CallSecureEndpoint() 
        { 
            string accessToken = await GetAccessToken();

            using HttpClient client = new();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            HttpResponseMessage response = await client.PostAsync(EndpointUrl, new StringContent(string.Empty) /*code to build the request body omitted*/); 

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                return content;
            }
            else
            {
                throw new HttpRequestException($"Failed to call secure endpoint with status code {response.StatusCode}");
            }
        }
    }
}
8fsztsew

8fsztsew1#

只要能够访问Azure AD和Azure OpenAI端点,在本地运行的应用程序就应该可以工作,因此请确保您的网络设置允许这一点。
您也可以使用Azure OpenAI .NET SDK进行调查,但请注意,它目前处于测试阶段。

相关问题