Microsoft Kiota Azure Authentication
The Microsoft Kiota Authentication Azure Library provides an implementation to authenticate HTTP requests for Kiota-generated API clients using `azure-identity`. It allows Python applications to securely access APIs protected by the Microsoft Entra Identity Platform. The library is actively maintained with frequent minor releases, typically on a monthly cadence, synchronizing versions with other Kiota Python packages.
Warnings
- gotcha Kiota-generated API clients do not inherently include authentication logic. You must explicitly instantiate and provide an `IAuthenticationProvider` (like `AzureIdentityAuthenticationProvider`) to the client or request adapter. Failing to do so will result in unauthenticated requests.
- gotcha The `azure-identity` library requires proper configuration of Azure AD application registrations. Issues like incorrect client IDs, unsupported authentication flows, or missing API permissions for your application will prevent token acquisition and result in authentication failures.
- breaking Major releases of Kiota tooling and its libraries (including authentication) are expected to contain breaking changes to their public API surface area. This means regenerating clients and updating library versions can require code adjustments.
- gotcha The `allowed_hosts` parameter in `AzureIdentityAuthenticationProvider` is critical for security. If the host of the API endpoint you are trying to reach is not in this list, the authentication provider will not attach the access token, leading to unauthorized errors from the API.
Install
-
pip install microsoft-kiota-authentication-azure
Imports
- AzureIdentityAuthenticationProvider
from microsoft_kiota_authentication_azure import AzureIdentityAuthenticationProvider
- DeviceCodeCredential
from azure.identity import DeviceCodeCredential
Quickstart
import os
import asyncio
from azure.identity import DeviceCodeCredential
from microsoft_kiota_authentication_azure import AzureIdentityAuthenticationProvider
from microsoft_kiota_http.httpx_request_adapter import HttpxRequestAdapter
from kiota_abstractions.request_information import RequestInformation, HttpMethod
from kiota_abstractions.serialization import ParseNodeFactoryRegistry, SerializationWriterFactoryRegistry
async def main():
# 1. Obtain a TokenCredential from azure-identity.
# For local development, DeviceCodeCredential is often used.
# Ensure you have registered an application in Azure AD and have its CLIENT_ID.
# Set AZURE_CLIENT_ID environment variable or pass client_id directly.
client_id = os.environ.get('AZURE_CLIENT_ID', 'YOUR_CLIENT_ID_HERE')
if client_id == 'YOUR_CLIENT_ID_HERE':
print("Please set the AZURE_CLIENT_ID environment variable or replace 'YOUR_CLIENT_ID_HERE'.")
return
credential = DeviceCodeCredential(client_id=client_id)
# 2. Create the AzureIdentityAuthenticationProvider.
# The allowed_hosts list is crucial for security, specifying which domains
# the authentication provider is allowed to send tokens to.
allowed_hosts = ["graph.microsoft.com", "yourtenant.onmicrosoft.com"]
auth_provider = AzureIdentityAuthenticationProvider(credential, allowed_hosts)
# 3. Create a RequestAdapter using the authentication provider.
# HttpxRequestAdapter is Kiota's default HTTP client implementation.
# You also need a ParseNodeFactoryRegistry and SerializationWriterFactoryRegistry
# for a fully functional adapter, even if not directly used in this simple auth example.
request_adapter = HttpxRequestAdapter(
auth_provider,
parse_node_factory=ParseNodeFactoryRegistry(),
serialization_writer_factory=SerializationWriterFactoryRegistry()
)
# 4. Illustrative use: Create a RequestInformation object and send it (conceptually).
# In a real scenario, this would be part of a Kiota-generated API client call.
request_info = RequestInformation(HttpMethod.GET, "https://graph.microsoft.com/v1.0/me")
print(f"\nAttempting to authenticate request to: {request_info.url_template}")
# The authenticate_request method is typically called internally by the RequestAdapter.
# We call it here to demonstrate its direct usage and token acquisition.
try:
await auth_provider.authenticate_request(request_info)
print("Authentication provider prepared the request with a token.")
if request_info.headers and 'Authorization' in request_info.headers:
print("Authorization header added successfully.")
else:
print("Authorization header not found after authentication.")
# In a real app, you'd then use request_adapter.send(request_info, ...) to make the call
print("\nQuickstart setup complete. You would now use this request_adapter with a Kiota-generated client.")
except Exception as e:
print(f"An error occurred during authentication: {e}")
print("Ensure your AZURE_CLIENT_ID is correct and your application registration supports the chosen credential type (e.g., Device Code Flow).")
if __name__ == '__main__':
asyncio.run(main())