Check! How to use Azure Key Vault with Azure SDK for Python! (Measures around authentication)

Good evening! @dz_ I'm Kazumi Ohira.

Prologue-Introduction

When I tried to use Azure Key Vault using the Azure SDK for Python, I struggled with RBAC (Role Based Access Control) authentication, so I was angry and dealt with the situation.

About RBAC authentication and auth file for SDK

After considering Azure credentials, I found that it can be handled as a json file in the following format.

For example, to issue a new RBAC certificate and output that information in the above JSON format, you can use the following Azure CLI 2.0 (https://docs.microsoft.com/en-us/cli/azure/install) -azure-cli "Install the Azure CLI 2.0 | Microsoft Docs") commands are available.

Issue RBAC authentication information with CLI (JSON output option for SDK)


$ az login
$ az ad sp create-for-rbac --sdk-auth > auth-sample.json

JSON sample for SDK (quoted from the above document)


{
    "clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e",
    "clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e",
    "subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e",
    "tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
    "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
    "resourceManagerEndpointUrl": "https://management.azure.com/",
    "activeDirectoryGraphResourceId": "https://graph.windows.net/",
    "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
    "galleryEndpointUrl": "https://gallery.azure.com/",
    "managementEndpointUrl": "https://management.core.windows.net/"
}

How to handle credentials in the SDK

Also, if you set the path of this JSON file in the environment variable ʻAZURE_AUTH_LOCATION`, the SDK will read it automatically.

And, as you can see in the link above, in most cases you can easily generate a client using ʻazure.common.client_factory.get_client_from_auth_file`.

How to use Azure Key Vault with Azure SDK for Python

KeyVaultClient doesn't allow get_client_from_auth_file ...

I see!

I thought that the Azure Key Vault client KeyVaultClient could be easily generated by the above method, so I tried it ... I can't (´ ・ ω ・`)

azure-keyvault version


$ pip show azure-keyvault
Name: azure-keyvault
Version: 0.3.5
...

An example that did not work with KeyVault Client


from azure.common.client_factory import get_client_from_auth_file
from azure.keyvault import KeyVaultClient
client = get_client_from_auth_file(KeyVaultClient)

Error when KeyVault Client does not work


Traceback (most recent call last):
  File "sample.py", line 26, in <module>
    client = get_client_from_auth_file(KeyVaultClient)
  File "/usr/local/lib/python2.7/dist-packages/azure/common/client_factory.py", line 192, in get_client_fr
om_auth_file
    return get_client_from_json_dict(client_class, config_dict, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/azure/common/client_factory.py", line 132, in get_client_fr
om_json_dict
    return _instantiate_client(client_class, **parameters)
  File "/usr/local/lib/python2.7/dist-packages/azure/common/client_factory.py", line 31, in _instantiate_c
lient
    return client_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'base_url'

Use this method to generate KeyVaultClient!

I glanced at the source code of the SDK, and finally arrived at this material, I was able to go this way! Yay! ヾ (o´∀`o) ノ

Since it's a big deal, I wrote a sample code that uses the path of ʻAZURE_AUTH_LOCATION` with reference to the above.

sample.py


#!/usr/bin/env python

import json
import os

from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials

def auth_callback(server, resource, scope):
    with open(os.environ.get('AZURE_AUTH_LOCATION')) as auth_file:
        auth = json.load(auth_file)

    credentials = ServicePrincipalCredentials(
        client_id=auth['clientId'],
        secret=auth['clientSecret'],
        tenant=auth['tenantId'],
        resource=resource
    )
    token = credentials.token
    return token['token_type'], token['access_token']

#Get a client
client = KeyVaultClient(KeyVaultAuthentication(auth_callback))

#Get a secret
vault_base_url = 'https://<Key Vault name>.vault.azure.net/'
secret_name = '<Secret name>'
secret_version = '' #If you do not specify the version

secret = client.get_secret(vault_base_url, secret_name, secret_version)

Regarding the acquisition of secrets, I referred to the following documents.

I recommend this! Yay! ヾ (o´∀`o) ノ

Epilogue-Conclusion

So, I was tossed a lot, but I can't stop the engineer because the SDK can be solved by reading the source code in open source, and I'm happy when I found out (o ゝ ω ・ o) ノ))

Recommended Posts

Check! How to use Azure Key Vault with Azure SDK for Python! (Measures around authentication)
Python: How to use async with
How to use FTP with Python
How to change the log level of Azure SDK for Python
How to use an external editor for Python development with Grasshopper
[Python] Organizing how to use for statements
How to use "deque" for Python data
How to use fingerprint authentication for KDE
How to access data with object ['key'] for your own Python class
How to use tkinter with python in pyenv
How to use Service Account OAuth and API with Google API Client for python
[For beginners] How to use say command in python!
How to use python interactive mode with git bash
Python # How to check type and type for super beginners
python3: How to use bottle (2)
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
[python] How to check if the Key exists in the dictionary
[python] How to use the library Matplotlib for drawing graphs
How to use Realsense's Python wrapper PyRealsense with Jetson Nano
[Hyperledger Iroha] Notes on how to use the Python SDK
Use Azure ML Python SDK 4: Write output to Blob storage-Part 2
How to use machine learning for work? 03_Python coding procedure
How to upload files to Cloud Storage with Firebase's python SDK
How to specify Cache-Control for blob storage in Azure Storage in Python
I didn't know how to use the [python] for statement
Use Azure ML Python SDK 3: Write output to Blob storage-Part 1
Let's use Watson from Python! --How to use Developer Cloud Python SDK
[Python] How to use Pandas Series
How to use Requests (Python Library)
How to use SQLite in Python
How to use virtualenv with PowerShell
[Python] Use Basic/Digest authentication with Flask
How to configure CORS settings for Azure storage service in Python
Sample to use after OAuth authentication of BOX API with Python
How to use python put in pyenv on macOS with PyCall
[Introduction to Python] How to use the in operator in a for statement?
How to get started with Python
[Python] How to use list 3 Added
How to use Mysql in python
[Python] Explains how to use the format function with an example
How to use OpenPose's Python API
[Python] How to get a value with a key other than value with Enum
How to use ChemSpider in Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to automatically install Chrome Driver for Chrome version with Python + Selenium + Chrome
How to calculate date with python
How to use python zip function
[Python] How to use Typetalk API
Use Azure AD for Linux authentication
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to set proxy, redirect and SSL authentication for Python Requests module