Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In your application code, you can set up a keyless connection to Azure AI Search that uses Microsoft Entra ID and roles for authentication and authorization. Application requests to most Azure services must be authenticated with keys or keyless connections. Developers must be diligent to never expose the keys in an unsecure location. Anyone who gains access to the key is able to authenticate to the service. Keyless authentication offers improved management and security benefits over the account key because there's no key (or connection string) to store.
This article explains how to use DefaultAzureCredential in your application code.
To implement keyless connections in your code, follow these steps:
- Enable role-based access on your search service
- Set environment variables, as needed.
- Use an Azure Identity library credential type to create an Azure AI Search client object.
Prerequisites
Azure AI Search, any region but it must be a billable tier (basic or higher).
Role-based access enabled on your search service.
Role assignments on Azure AI Search. Assign these roles to your identity:
- Search Service Contributor and Search Index Data Contributor for local development (full access)
- Search Index Data Reader for production read-only queries
For step-by-step instructions, see Assign roles for development.
Install Azure Identity client library
To use a keyless approach, update your AI Search enabled code with the Azure Identity client library.
Install the Azure Identity client library for .NET and the Azure Search Documents client library:
dotnet add package Azure.Identity
dotnet add package Azure.Search.Documents
Update source code to use DefaultAzureCredential
The Azure Identity library's DefaultAzureCredential allows you to run the same code in the local development environment and in the Azure cloud. Create a single credential and reuse the credential instance as needed to take advantage of token caching.
For more information on DefaultAzureCredential for .NET, see Azure Identity client library for .NET.
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Azure.Identity;
using System;
using static System.Environment;
string endpoint = GetEnvironmentVariable("AZURE_SEARCH_ENDPOINT");
string indexName = "my-search-index";
DefaultAzureCredential credential = new();
SearchClient searchClient = new(new Uri(endpoint), indexName, credential);
SearchIndexClient searchIndexClient = new(endpoint, credential);
Reference: SearchClient, SearchIndexClient, DefaultAzureCredential
Verify your connection
After setting up the client, verify your connection by running a simple operation. The following example lists indexes on your search service:
// List indexes to verify connection
var indexes = searchIndexClient.GetIndexNames();
foreach (var name in indexes)
{
Console.WriteLine(name);
}
A successful connection prints the names of your indexes (or an empty list if no indexes exist). If you receive an authentication error, verify that role-based access is enabled and your identity has the required role assignments.
The default authority is Azure public cloud. Custom audience values for sovereign or specialized clouds include:
https://search.azure.usfor Azure Governmenthttps://search.azure.cnfor Azure operated by 21Vianethttps://search.microsoftazure.defor Azure Germany
Local development
Local development using roles includes these steps:
- Assign your personal identity to RBAC roles on the specific resource.
- Use a tool like the Azure CLI or Azure PowerShell to authenticate with Azure.
- Establish environment variables for your resource.
Roles for local development
As a local developer, your Azure identity needs full control over data plane operations. These are the suggested roles:
- Search Service Contributor, create and manage objects
- Search Index Data Contributor, load and query an index
Find your personal identity with one of the following tools. Use that identity as the <identity-id> value.
Replace placeholders <role-name>, <identity-id>, <subscription-id>, and <resource-group-name> with your actual values in the following commands.
Sign in to Azure CLI.
az loginA browser window opens for authentication. After successful sign-in, the terminal displays your subscription information.
Get your personal identity.
az ad signed-in-user show \ --query id -o tsvThe command returns your user object ID (a GUID). Save this value for the next step.
Assign the role-based access control (RBAC) role to the identity for the resource group.
az role assignment create \ --role "<role-name>" \ --assignee "<identity-id>" \ --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>"A successful assignment returns a JSON object with the role assignment details.
Authentication for local development
Use a tool in your local development environment to authentication to Azure identity. Once you're authenticated, the DefaultAzureCredential instance in your source code finds and uses your identity for authentication purposes.
Select a tool for authentication during local development.
Configure environment variables for local development
To connect to Azure AI Search, your code needs to know your resource endpoint.
Create an environment variable named AZURE_SEARCH_ENDPOINT for your Azure AI Search endpoint. This URL generally has the format https://<YOUR-RESOURCE-NAME>.search.windows.net/.
Production workloads
Deploy production workloads includes these steps:
- Choose RBAC roles that adhere to the principle of least privilege.
- Assign RBAC roles to your production identity on the specific resource.
- Set up environment variables for your resource.
Roles for production workloads
To create your production resources, you need to create a user-assigned managed identity then assign that identity to your resources with the correct roles.
The following role is suggested for a production application:
| Role name | Id |
|---|---|
| Search Index Data Reader | 1407120a-92aa-4202-b7e9-c0e197c71c8f |
Authentication for production workloads
Use the following Azure AI Search Bicep template to create the resource and set the authentication for the identityId. Bicep requires the role ID. The name shown in this Bicep snippet isn't the Azure role; it's specific to the Bicep deployment.
// main.bicep
param environment string = 'production'
param roleGuid string = ''
module aiSearchRoleUser 'core/security/role.bicep' = {
scope: aiSearchResourceGroup
name: 'aiSearch-role-user'
params: {
principalId: (environment == 'development') ? principalId : userAssignedManagedIdentity.properties.principalId
principalType: (environment == 'development') ? 'User' : 'ServicePrincipal'
roleDefinitionId: roleGuid
}
}
The main.bicep file calls the following generic Bicep code to create any role. You have the option to create multiple RBAC roles, such as one for the user and another for production. This allows you to enable both development and production environments within the same Bicep deployment.
// core/security/role.bicep
metadata description = 'Creates a role assignment for an identity.'
param principalId string // passed in from main.bicep
@allowed([
'Device'
'ForeignGroup'
'Group'
'ServicePrincipal'
'User'
])
param principalType string = 'ServicePrincipal'
param roleDefinitionId string // Role ID
resource role 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(subscription().id, resourceGroup().id, principalId, roleDefinitionId)
properties: {
principalId: principalId
principalType: principalType
roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionId)
}
}
Configure environment variables for production workloads
To connect to Azure AI Search, your code needs to know your resource endpoint, and the ID of the managed identity.
Create environment variables for your deployed and keyless Azure AI Search resource:
AZURE_SEARCH_ENDPOINT: This URL is the access point for your Azure AI Search resource. This URL generally has the formathttps://<YOUR-RESOURCE-NAME>.search.windows.net/.AZURE_CLIENT_ID: This is the identity to authenticate as.
Troubleshoot common errors
| Error | Cause | Solution |
|---|---|---|
AuthenticationFailedException |
Missing or invalid credentials | Ensure you're signed in with az login (CLI) or Connect-AzAccount (PowerShell). Verify your Azure account has access to the subscription. |
403 Forbidden |
Identity lacks required role | Assign the appropriate role (Search Index Data Reader for queries, Search Index Data Contributor for indexing). Role assignments can take up to 10 minutes to propagate. |
401 Unauthorized |
RBAC not enabled on search service | Enable role-based access in the Azure portal under Settings > Keys > Role-based access control. |
ResourceNotFoundException |
Invalid endpoint or index name | Verify the AZURE_SEARCH_ENDPOINT environment variable matches your search service URL (format: https://<service-name>.search.windows.net). |
CredentialUnavailableException |
No valid credential found | DefaultAzureCredential tries multiple authentication methods. Ensure at least one is configured (Azure CLI, Visual Studio, environment variables). |