Microsoft Kiota Azure Authentication

1.9.10 · active · verified Mon Apr 06

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

Install

Imports

Quickstart

This quickstart demonstrates how to set up the `AzureIdentityAuthenticationProvider` with an `azure-identity` credential (like `DeviceCodeCredential`) and integrate it into a `HttpxRequestAdapter`. It highlights the essential steps to prepare an authenticated request, typically used by a Kiota-generated API client. Remember to replace 'YOUR_CLIENT_ID_HERE' or set the `AZURE_CLIENT_ID` environment variable with your Azure AD application's client ID. Also, configure your Azure application registration to support the Device Code Flow for this example.

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())

view raw JSON →