As organizations introduce AI into more applications, controlling who can access each model becomes an important part of application security. A development team may use one model for document summarization, another for customer support, and a third for internal code analysis. Not every application or user should automatically have access to all of them.
Managing permissions separately in every application can quickly become difficult. Developers may end up maintaining API keys in configuration files, sharing credentials between services, and implementing different authorization rules for different AI providers.
Azure AI Gateway provides a central place to manage access to published AI models and tools. Applications send requests to the gateway, while administrators use Microsoft Entra ID and Azure role-based access control (RBAC) to decide which identities can invoke particular models.
This is especially useful in enterprise .NET applications where different teams have different responsibilities. A customer support application may need access to a support model, while an internal reporting application may only need a summarization model.
In this article, we will configure model access using Azure AI Gateway, understand the difference between runtime and administrative permissions, and build a C# application that authenticates with Microsoft Entra ID instead of storing a gateway API key.
Understanding the Three Security Boundaries
Before implementing access control, it is important to understand that Azure AI Gateway involves three separate security relationships.
The first is administrator-to-gateway access. This controls who can create or modify gateway resources, register models, configure aliases, manage policies, and change gateway settings.
The second is application-to-gateway access. This controls which users, applications, or managed identities can invoke models and tools through the gateway.
The third is gateway-to-backend access. This determines how the gateway authenticates to the actual model provider, such as Microsoft Foundry or another supported service.
These relationships are independent. Giving an application permission to invoke a model does not give it permission to change the gateway configuration. Similarly, giving the gateway a managed identity to access Microsoft Foundry does not automatically authorize every application to call the gateway.
Consider an organization with three teams:
- The customer support team uses a model for customer queries.
- The reporting team uses a model for summarizing business documents.
- The platform team manages model registrations, aliases, and gateway policies.
The support application should not automatically receive access to the reporting model. The reporting application should not be able to modify gateway configuration. The platform team may need administrative access without necessarily having permission to invoke models.
Separating these permissions makes the gateway easier to secure and operate.
Choosing Between API Keys and Microsoft Entra ID
Azure AI Gateway supports runtime API keys and Microsoft Entra ID authentication for applications calling models and tools.
Runtime API keys are convenient for initial integration. An administrator creates a key in the gateway, and the application sends it with each request.
However, the dedicated Azure AI Gateway runtime API keys are gateway-scoped. A key grants access across the gateway rather than restricting the caller to one particular model alias. This makes them less suitable when different applications need different model permissions.
Microsoft Entra ID provides a more flexible approach. Each user, application, service principal, or managed identity can authenticate using its own identity. Azure RBAC then determines which gateway resources that identity can access.
For example, an application can receive permission to invoke one model alias without receiving permission to invoke every other model.
The difference is important:
Area | Runtime API key | Microsoft Entra ID |
Authentication | Shared secret | Identity-based token |
Permission model | Gateway-wide runtime access | Azure RBAC |
Model-specific access | Not restricted by individual runtime key | Can be scoped to a model alias |
Credential management | Key creation, rotation, and revocation | Identity and role assignment management |
Azure-hosted applications | Requires secure key storage | Can use managed identity |
User and application identity | Key identifies the credential | Token identifies the caller |
For production applications, Microsoft Entra ID is generally a better starting point when access needs to be separated by application, user, or team.
Understanding Azure AI Gateway Runtime Roles
Azure AI Gateway provides runtime roles that control which models and tools an identity can use.
The main roles are:
Role | Permission |
AI Gateway User | List and invoke models, and list and call MCP tools |
AI Gateway Models User | List and invoke models |
AI Gateway Tools User | List and call tools within MCP servers |
The scope of the assignment is just as important as the role itself.
For example, assigning AI Gateway Models User at the default workspace scope allows the identity to access all models in that workspace. Assigning the same role directly to a model alias limits the assignment to that alias.
This allows administrators to follow the principle of least privilege: give an identity only the permissions it needs to perform its task.
Suppose an organization has two model aliases:
customer-support
document-summary
The support application only needs customer-support. Instead of granting access to the entire gateway workspace, the administrator can assign AI Gateway Models User directly to that alias.
The reporting application can receive a separate assignment for document-summary.
This makes the access model easier to understand and reduces unnecessary permissions.
Configuring Model Access in Azure AI Gateway
Assume that a gateway has already been created and at least one model has been registered. The model should have a callable alias that the application can use.
For this example, use the alias:
customer-support
Open the Azure AI Gateway portal and select the gateway.
Navigate to Access and open the Entra ID section. Start a new role assignment and select the identity that needs access.
The identity can be an individual user, an Entra ID group, a service principal, or a managed identity.
For an enterprise application, using a managed identity or an appropriate application identity is preferable to sharing a developer's personal identity. For groups of employees, assigning access to an Entra ID group can simplify onboarding and offboarding.
When choosing the access type, select the option that grants runtime invocation without granting gateway management permissions.
Next, select the runtime role. For an application that only needs to call models, choose AI Gateway Models User.
Finally, select the narrowest appropriate scope. In this example, select the customer-support model alias rather than all gateway assets.
The role assignment now allows the selected identity to invoke that model alias. It does not give the identity permission to modify the model registration or gateway configuration.
An administrator can verify the assignment under Access and Entra ID.
Understanding Model-Level RBAC Scope
Azure RBAC assignments use resource IDs to identify the resource where permissions apply.
The default workspace resource ID follows this structure:
<gateway-resource-id>/workspaces/default
A model alias has a more specific scope:
<gateway-resource-id>/workspaces/default/aliases/customer-support
For example, a gateway resource ID might look like this:
/subscriptions/00000000-0000-0000-0000-000000000000
/resourceGroups/AIPlatformRG
/providers/Microsoft.ApiManagement/aigateways/company-ai
The model alias scope would then be:
/subscriptions/00000000-0000-0000-0000-000000000000
/resourceGroups/AIPlatformRG
/providers/Microsoft.ApiManagement/aigateways/company-ai
/workspaces/default/aliases/customer-support
The subscription ID and resource names above are illustrative. Use the actual resource ID and alias from your Azure environment.
This resource-level assignment is what makes it possible to give two applications different model permissions even when they use the same gateway endpoint.
Calling Azure AI Gateway From C# With Microsoft Entra ID
Once the identity has the required runtime role, the .NET application can authenticate using DefaultAzureCredential.
This approach avoids storing a gateway runtime API key in the application configuration.
First, create a console application:
dotnet new console -n SecureAIGatewayDemo
cd SecureAIGatewayDemo
Install the Azure Identity package:
dotnet add package Azure.Identity
For local development, sign in using the Azure CLI:
az login
Configure the gateway URL and model alias as environment variables:
$env:AI_GATEWAY_URL = "https://your-gateway-host"
$env:AI_GATEWAY_MODEL = "customer-support"
Use the actual runtime hostname shown in your gateway configuration.
Now create a C# client that obtains an access token and sends a chat completion request.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Azure.Core;
using Azure.Identity;
public sealed class SecureAIGatewayClient
{
private const string GatewayScope =
"https://ai.gateway.azure.com/.default";
private readonly HttpClient _httpClient;
private readonly TokenCredential _credential;
private readonly string _gatewayUrl;
private readonly string _modelAlias;
public SecureAIGatewayClient(
HttpClient httpClient,
string gatewayUrl,
string modelAlias)
{
_httpClient = httpClient;
_gatewayUrl = gatewayUrl.TrimEnd('/');
_modelAlias = modelAlias;
_credential = new DefaultAzureCredential();
}
public async Task<string> SendAsync(
string prompt,
CancellationToken cancellationToken = default)
{
AccessToken token = await _credential.GetTokenAsync(
new TokenRequestContext(
new[] { GatewayScope }),
cancellationToken);
var requestBody = new
{
model = _modelAlias,
messages = new[]
{
new
{
role = "user",
content = prompt
}
}
};
using var request = new HttpRequestMessage(
HttpMethod.Post,
$"{_gatewayUrl}/default/models/openai/v1/chat/completions")
{
Content = JsonContent.Create(requestBody)
};
request.Headers.Authorization =
new AuthenticationHeaderValue(
"Bearer",
token.Token);
using var response = await _httpClient.SendAsync(
request,
cancellationToken);
string responseBody = await response.Content.ReadAsStringAsync(
cancellationToken);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(
$"Gateway returned {(int)response.StatusCode}: {responseBody}",
null,
response.StatusCode);
}
using var json = JsonDocument.Parse(responseBody);
return json.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString() ?? string.Empty;
}
}
The important part is the authentication flow.
DefaultAzureCredential uses an available credential source. During local development, it can use an authenticated Azure CLI or supported development-tool identity. When the application runs in Azure, it can use a configured managed identity.
The application requests a token for:
https://ai.gateway.azure.com/.default
The token is then sent in the HTTP Authorization header using the Bearer scheme.
Notice that the application does not send a gateway API key. It also does not need the backend model provider's credentials.
The gateway validates the token and checks the identity's runtime role assignment for the requested model alias. If the identity has permission, the request can proceed to the configured backend.
The example uses the OpenAI-compatible Chat Completions endpoint. The response parsing assumes a standard chat completion response with a text message. If the selected model uses a different API contract, adapt the request and response handling accordingly.
Running the Application
The application can now create the client and send a prompt.
string gatewayUrl =
Environment.GetEnvironmentVariable("AI_GATEWAY_URL")
?? throw new InvalidOperationException(
"AI_GATEWAY_URL is missing.");
string modelAlias =
Environment.GetEnvironmentVariable("AI_GATEWAY_MODEL")
?? throw new InvalidOperationException(
"AI_GATEWAY_MODEL is missing.");
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(90)
};
var client = new SecureAIGatewayClient(
httpClient,
gatewayUrl,
modelAlias);
Console.Write("Enter your question: ");
string prompt = Console.ReadLine() ?? string.Empty;
if (string.IsNullOrWhiteSpace(prompt))
{
Console.WriteLine("Enter a valid question.");
return;
}
try
{
string answer = await client.SendAsync(prompt);
Console.WriteLine();
Console.WriteLine("AI Response:");
Console.WriteLine(answer);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
catch (AuthenticationFailedException ex)
{
Console.WriteLine($"Authentication failed: {ex.Message}");
}
catch (TaskCanceledException)
{
Console.WriteLine("The request timed out or was cancelled.");
}
During local development, make sure the Azure CLI identity used by DefaultAzureCredential has been assigned the appropriate runtime role.
When the application runs in Azure, configure a managed identity and assign the same runtime role to that identity. The application code can continue using DefaultAzureCredential without introducing a separate API key configuration.
For a production service, use IHttpClientFactory and dependency injection rather than creating a new HttpClient for every request. Also keep the gateway endpoint and alias in configuration and apply appropriate logging without recording access tokens or sensitive prompt content.
Understanding 401 and 403 Errors
Authentication and authorization failures are different, and knowing the difference makes troubleshooting much easier.
A 401 Unauthorized response generally means that the gateway could not accept the caller's authentication. The token may be missing, expired, invalid, or issued for the wrong audience.
Check that the application requests the correct gateway token scope and sends it in the Authorization header. Also make sure that an older API-key header is not being sent alongside the Entra bearer token. The gateway's documented runtime authentication flow does not expect both credentials in the same request.
A 403 Forbidden response generally means that the caller was authenticated but does not have permission to invoke the requested model or tool.
For this error, check the identity used by the application and verify its RBAC assignment. Confirm that the role is a runtime role, that it is assigned at the correct scope, and that the requested model alias matches the resource where access was granted.
For example, an application might have AI Gateway Models User on customer-support but attempt to invoke document-summary. Authentication succeeds, but authorization fails because the identity does not have access to the second alias.
Role assignments can take some time to become effective. If the assignment was created recently, wait for it to propagate and then retry.
Separating Runtime Access From Gateway Administration
A common security mistake is giving an application or deployment pipeline broad administrative permissions simply because it needs to call an AI model.
Azure AI Gateway separates runtime roles from control-plane roles.
For example, AI Gateway Developer provides read access to gateway asset configuration. AI Gateway Contributor allows authorized users to create, modify, and delete gateway assets such as providers, models, aliases, and MCP servers. Azure Contributor provides broader management access to the gateway resource.
These management roles do not automatically grant runtime model invocation.
This separation is useful when organizing responsibilities across development and platform teams.
A developer may need to inspect a model alias without being allowed to modify it. A platform engineer may need to register new models and configure routing. An application identity may only need permission to invoke one alias.
Assigning separate roles for these responsibilities reduces the risk of accidental configuration changes and unnecessary access to model resources.
Using Managed Identity for Azure-Hosted Applications
For applications running in Azure, managed identity is usually preferable to storing client secrets or gateway API keys.
For example, an ASP.NET Core API hosted in Azure App Service can use its system-assigned managed identity to request an access token.
The application still uses DefaultAzureCredential:
var credential = new DefaultAzureCredential();
AccessToken token = await credential.GetTokenAsync(
new TokenRequestContext(
new[]
{
"https://ai.gateway.azure.com/.default"
}));
There is no need to place a client secret in appsettings.json. Azure manages the identity credentials for the application.
However, enabling a managed identity is only one part of the setup. An administrator must also assign the appropriate AI Gateway runtime role to that identity.
The gateway uses its own configured identity or backend credential when communicating with the model provider. The application's managed identity and the gateway's backend identity serve different purposes.
Keeping these identities separate makes it easier to control and audit access across the entire request path.
Designing a Practical Access Strategy
For an organization using several AI applications, a useful starting point is to create a separate identity for each application and assign permissions only to the model aliases it requires.
For example:
Application identity | Runtime role | Scope |
Support API | AI Gateway Models User | customer-support
|
Reporting API | AI Gateway Models User | document-summary
|
Internal AI agent | AI Gateway User | Default workspace, if it needs both models and MCP tools |
Platform engineer | AI Gateway Contributor | Default workspace |
This is an illustrative access design. The actual role and scope should reflect the application's responsibilities.
For employee-facing applications, group-based access can simplify permission management. For Azure-hosted services, managed identities avoid distributing credentials. For automated deployment pipelines, use a dedicated identity with only the control-plane permissions required by the deployment process.
Review access periodically. Remove assignments for retired applications and users who no longer need access. Keep runtime permissions separate from administrative permissions, and avoid granting workspace-wide access when a model-level assignment is sufficient.
Conclusion
Azure AI Gateway provides a central way to control which applications, users, and services can invoke AI models. Microsoft Entra ID and Azure RBAC make it possible to assign runtime permissions to individual model aliases instead of relying entirely on shared gateway-wide API keys.
For .NET developers, DefaultAzureCredential provides a practical way to authenticate through Microsoft Entra ID. The same application code can use a developer's authenticated identity during local development and a managed identity when deployed to Azure.
The most important design decision is to separate gateway administration, application runtime access, and backend authentication. Once these boundaries are clear, it becomes easier to give each application the permissions it needs without exposing every model or gateway configuration to every caller.
Azure AI GatewayMicrosoft Entra IDAzure RBACAI model access.NETC#
Join the conversation! Your thoughts help the community grow.