Search code examples
c#azureazure-active-directoryazure-openai

Obtain an Azure AD access token to call an Azure OpenAI resource's endpoint from an on-premises application


I have to call my Azure OpenAI resource's ChatCompletions endpoint from the C# code of my on-prem application.

I have the following code. I will obtain the client Id and client secret after I register my application with Azure Active Directory.

Is this going to work given that my application is on-premises, not migrated to Azure yet?

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}");
            }
        }
    }
}

Solution

  • The code worked. The Object ID of the enterprise application (managed application in local directory - the service principal) corresponding to the app registration was added to Cognitive Services OpenAI User role of the Azure OpenAI resource.