skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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 User role of the Azure OpenAI resource.


  2. Applications running on-premises should work as long as they are able to access both Azure AD and Azure OpenAI endpoints, so ensure your network setup allows this.

    You could also investigate using the Azure OpenAI .NET SDK but do note that it is currently in beta.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search