Во время аутентификации браузер открывается дважды — по одному для каждой службы. Из-за кэширования мне приходится делать это только при первом входе пользователя в систему, хотя я все равно считаю, что это нехорошее поведение.
Код: Выделить всё
import os
from azure.identity import InteractiveBrowserCredential, TokenCachePersistenceOptions, AuthenticationRecord
from azure.keyvault.secrets import SecretClient
from azure.mgmt.resourcegraph import ResourceGraphClient
from azure.mgmt.resourcegraph.models import QueryRequest
tenant_id = "my_tenant_id"
keyvault_name = "my_keyvaut_name"
VAULT_SCOPE = "https://vault.azure.net/.default"
MANAGEMENT_SCOPE = "https://management.azure.com/.default"
AUTH_RECORD_FILE = "auth_record.json"
cache_options = TokenCachePersistenceOptions(name="my_app_cache")
# Try to load existing authentication record
authentication_record = None
if os.path.exists(AUTH_RECORD_FILE):
try:
with open(AUTH_RECORD_FILE, "r") as f:
record_json = f.read()
authentication_record = AuthenticationRecord.deserialize(record_json)
print("Loaded cached authentication record")
except Exception as e:
print(f"ERROR: Failed to load auth record: {e}")
credential = InteractiveBrowserCredential(
tenant_id=tenant_id,
cache_persistence_options=cache_options,
authentication_record=authentication_record
)
# First authentication (browser opens here if no cached record)
try:
# record = credential.authenticate(scopes=[VAULT_SCOPE, MANAGEMENT_SCOPE], enable_cae=True) # ERROR -> Accept only 1 scope at a time
record = credential.authenticate(scopes=[VAULT_SCOPE], enable_cae=True) # First browser authentication
print("Authenticated with CAE for Key Vault")
# Save the authentication record for next time
if record and not os.path.exists(AUTH_RECORD_FILE):
with open(AUTH_RECORD_FILE, "w") as f:
f.write(record.serialize())
print("Saved authentication record for future use")
print("Authentication successful")
except Exception as e:
print(f"Authentication failed: {e}")
raise
# Test vault connection
vault_url = f"https://{keyvault_name}.vault.azure.net"
secret_client = SecretClient(vault_url=vault_url, credential=credential)
next(secret_client.list_properties_of_secrets(max_page_size=1))
# Get keyvault info
resource_client = ResourceGraphClient(credential)
query = f'Resources | where type == "microsoft.keyvault/vaults" | where name == "{keyvault_name}" | project resourceGroup, subscriptionId, id'
request = QueryRequest(query=query, subscriptions=[])
response = resource_client.resources(request) # Second browser authentication
print(response)
- python 3.13.11
- azure-identity 1.23.0
- azure-keyvault-secrets 4.9.0
- azure-mgmt-resourcegraph 25.2
Небольшая дополнительная информация: аутентификация для областей графа создает файл кэша nocae, а аутентификация областей хранилища создает файл кэша cae. После того, как эти файлы созданы в первый раз, пользователь может пройти аутентификацию без необходимости интерактивного входа в систему.
Можно ли будет войти в систему только один раз, сохраняя при этом возможность получать токены из двух разных областей?
Подробнее здесь: https://stackoverflow.com/questions/798 ... opes-azure
Мобильная версия