Skip to main content

Lab 2: Manage AI Services Security


https://microsoftlearning.github.io/AI-102-AIEngineer/Instructions/02-cognitive-services-security.html

Prerequisites


  1. Open up the mslearn-ai-services folder from the GitHub repository
  2. Provision an Azure AI Services multi-service account
  3. Take note of your key and endpoint
  4. Log into Azure using az login

List your keys using Azure CLI


az cognitiveservices account keys list --name <resourceName> --resource-group <resourceGroup>

image.png

  1. You can test your multi-service by using the following curl:
curl -X POST "<yourEndpoint>/text/analytics/v3.0/languages?" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: <yourKey>" --data-ascii "{'documents':[{'id':1,'text':'hello'}]}"

image.png

Regenerating keys


az cognitiveservices account keys regenerate --name <resourceName> --resource-group <resourceGroup> --key-name key1

Now run the CURL command with the old key and the new key.

Using a Key Vault


  1. Create a key vault
  2. Create an access policy with your user.
  3. Create a new secret called AI-Services-Key and then put your key as the value.

image.png 4. Create a service principal for your application. az ad sp create-for-rbac -n "api://<spName>" --role owner --scopes subscriptions/<subscriptionId>/resourceGroups/<resourceGroup> 5. Take note of the password that it creates image.png

  1. Add this application to the Key Vault Access Policy with get and list permissions to the secrets.

image.png

  1. In your VS Code, update the keyvault-client/.env file with all of the information required.
    image.png
  2. Install the packages:
pip install azure-ai-textanalytics==5.3.0
pip install azure-identity==1.5.0
pip install azure-keyvault-secrets==4.2.0
  1. Run the program: python keyvault-client.py

Notice that it grabs the value from the KeyVault and uses that in the script. NOTE: I use this script to test my private endpoint and KeyVault deployments.
image.png

Code:

keyvault-client.py

keyvault-client.py
from dotenv import load_dotenv
import os
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential


def main():
global ai_endpoint
global cog_key

try:
# Get Configuration Settings
load_dotenv()
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
key_vault_name = os.getenv('KEY_VAULT')
app_tenant = os.getenv('TENANT_ID')
app_id = os.getenv('APP_ID')
app_password = os.getenv('APP_PASSWORD')

# Get Azure AI services key from keyvault using the service principal credentials
key_vault_uri = f"https://{key_vault_name}.vault.azure.net/"
credential = ClientSecretCredential(app_tenant, app_id, app_password)
keyvault_client = SecretClient(key_vault_uri, credential)
secret_key = keyvault_client.get_secret("AI-Services-Key")
cog_key = secret_key.value

# Get user input (until they enter "quit")
userText =''
while userText.lower() != 'quit':
userText = input('\nEnter some text ("quit" to stop)\n')
if userText.lower() != 'quit':
language = GetLanguage(userText)
print('Language:', language)

except Exception as ex:
print(ex)

def GetLanguage(text):

# Create client using endpoint and key
credential = AzureKeyCredential(cog_key)
client = TextAnalyticsClient(endpoint=ai_endpoint, credential=credential)

# Call the service to get the detected language
detectedLanguage = client.detect_language(documents = [text])[0]
return detectedLanguage.primary_language.name


if __name__ == "__main__":
main()

.env file


keyvault-client.py
AI_SERVICE_ENDPOINT=https://duposmultiservice01.cognitiveservices.azure.com/
KEY_VAULT=duposkeyvault
TENANT_ID=6a0...
APP_ID=79a...
APP_PASSWORD=R2...