|
| 1 | +# ------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# ------------------------------------ |
| 5 | +"""Demonstrates user authentication using InteractiveBrowserCredential. DeviceCodeCredential supports the same API.""" |
| 6 | + |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from azure.identity import AuthenticationRecord, InteractiveBrowserCredential |
| 10 | +from azure.keyvault.secrets import SecretClient |
| 11 | + |
| 12 | + |
| 13 | +# This sample uses Key Vault only for demonstration. Any client accepting azure-identity credentials will work the same. |
| 14 | +VAULT_URL = os.environ.get("VAULT_URL") |
| 15 | +if not VAULT_URL: |
| 16 | + print("This sample expects environment variable 'VAULT_URL' to be set with the URL of a Key Vault.") |
| 17 | + sys.exit(1) |
| 18 | + |
| 19 | + |
| 20 | +# Persistent caching is optional. By default, interactive credentials cache in memory only. |
| 21 | +credential = InteractiveBrowserCredential(enable_persistent_cache=True) |
| 22 | + |
| 23 | +# The 'authenticate' method begins interactive authentication. Call it whenever it's convenient |
| 24 | +# for your application to authenticate a user. It returns a record of the authentication. |
| 25 | +record = credential.authenticate() |
| 26 | + |
| 27 | +# The record contains no authentication secrets. You can serialize it to JSON for storage. |
| 28 | +record_json = record.serialize() |
| 29 | + |
| 30 | +# An authenticated credential is ready for use with a client. This request should succeed |
| 31 | +# without prompting for authentication again. |
| 32 | +client = SecretClient(VAULT_URL, credential) |
| 33 | +secret_names = [s.name for s in client.list_properties_of_secrets()] |
| 34 | + |
| 35 | +# With persistent caching enabled, an authentication record stored by your application enables |
| 36 | +# credentials to access data from past authentications. If the cache contains sufficient data, |
| 37 | +# this eliminates the need for your application to prompt for authentication every time it runs. |
| 38 | +deserialized_record = AuthenticationRecord.deserialize(record_json) |
| 39 | +new_credential = InteractiveBrowserCredential(enable_persistent_cache=True, authentication_record=deserialized_record) |
| 40 | + |
| 41 | +# This request should also succeed without prompting for authentication. |
| 42 | +client = SecretClient(VAULT_URL, new_credential) |
| 43 | +secret_names = [s.name for s in client.list_properties_of_secrets()] |
0 commit comments