How can i authenticate using token instead of api key for azure searchClient?

57 Views Asked by At

I am trying to use the searchClient library:

service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] 
index_name = os.environ["AZURE_SEARCH_INDEX_NAME"]
key = os.environ["AZURE_SEARCH_API_KEY"]
search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

Is there a way to create the searchclient by passing a token instead of an API or another way to authenticate without this api key?

1

There are 1 best solutions below

2
JayashankarGS On

As @Gaurav Mantri mentioned, you need to use DefaultAzureCredential to authorize through a token.

Here is the corrected code:

from azure.search.documents import SearchClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
endpoint = "https://<resource_name>.search.windows.net"
index_name = "hotels-2"
client = SearchClient(endpoint=endpoint, index_name=index_name, credential=credential)

DefaultAzureCredential authenticates through various mechanisms. Learn more about it here.

Output:

Enter image description here

Ensure you provide all required roles for accessing the AI search service.