Microsoft Azure Media Services Client Library for Python - A management library for Azure Media Services that provides programmatic access to media processing and streaming capabilities in the cloud.
83
Quality
Pending
Does it follow best practices?
Impact
83%
1.09xAverage score across 10 eval scenarios
Comprehensive content protection capabilities through content key policies, encryption configurations, and DRM integration. Supports multiple encryption schemes including PlayReady, Widevine, FairPlay, and AES envelope encryption with token-based access control and license delivery services.
Create and manage content key policies that define encryption and access control rules for protected content.
def list(resource_group_name: str, account_name: str) -> Iterable[ContentKeyPolicy]:
"""
List all content key policies in a media service account.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
Returns:
Iterable of ContentKeyPolicy objects with encryption configuration
"""
def get(
resource_group_name: str,
account_name: str,
content_key_policy_name: str
) -> ContentKeyPolicy:
"""
Get a specific content key policy with complete configuration.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- content_key_policy_name: Name of the content key policy (str)
Returns:
ContentKeyPolicy object with encryption and access control settings
"""
def create_or_update(
resource_group_name: str,
account_name: str,
content_key_policy_name: str,
parameters: ContentKeyPolicy
) -> ContentKeyPolicy:
"""
Create or update a content key policy.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- content_key_policy_name: Name for the content key policy (str)
- parameters: Content key policy configuration (ContentKeyPolicy)
Returns:
Created or updated ContentKeyPolicy object
"""
def update(
resource_group_name: str,
account_name: str,
content_key_policy_name: str,
parameters: ContentKeyPolicy
) -> ContentKeyPolicy:
"""
Update an existing content key policy.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- content_key_policy_name: Name of the content key policy (str)
- parameters: Updated content key policy configuration (ContentKeyPolicy)
Returns:
Updated ContentKeyPolicy object
"""
def delete(
resource_group_name: str,
account_name: str,
content_key_policy_name: str
) -> None:
"""
Delete a content key policy.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- content_key_policy_name: Name of the content key policy (str)
Returns:
None
"""Retrieve content key policy configuration including sensitive information like encryption keys.
def get_policy_properties_with_secrets(
resource_group_name: str,
account_name: str,
content_key_policy_name: str
) -> ContentKeyPolicyProperties:
"""
Get content key policy with sensitive information included.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- content_key_policy_name: Name of the content key policy (str)
Returns:
ContentKeyPolicyProperties with complete policy configuration including secrets
"""Retrieve content keys for streaming locators with encryption configurations.
def list_content_keys(
resource_group_name: str,
account_name: str,
streaming_locator_name: str
) -> ListContentKeysResponse:
"""
List content keys for an encrypted streaming locator.
Parameters:
- resource_group_name: Name of the resource group (str)
- account_name: Name of the media service account (str)
- streaming_locator_name: Name of the streaming locator (str)
Returns:
ListContentKeysResponse containing content encryption keys
"""class ContentKeyPolicy:
"""Content protection policy with encryption and access control."""
name: str
description: str
options: List[ContentKeyPolicyOption]
policy_id: str
created: str
last_modified: str
class ContentKeyPolicyOption:
"""Individual policy option with configuration and restrictions."""
policy_option_id: str
name: str
configuration: ContentKeyPolicyConfiguration
restriction: ContentKeyPolicyRestriction
class ContentKeyPolicyProperties:
"""Content key policy properties including sensitive data."""
policy_id: str
created: str
last_modified: str
description: str
options: List[ContentKeyPolicyOption]
# Policy Configurations
class ContentKeyPolicyConfiguration:
"""Base class for content key policy configurations."""
pass
class ContentKeyPolicyPlayReadyConfiguration(ContentKeyPolicyConfiguration):
"""PlayReady DRM configuration."""
licenses: List[ContentKeyPolicyPlayReadyLicense]
response_custom_data: str
class ContentKeyPolicyWidevineConfiguration(ContentKeyPolicyConfiguration):
"""Widevine DRM configuration."""
widevine_template: str
class ContentKeyPolicyClearKeyConfiguration(ContentKeyPolicyConfiguration):
"""Clear key configuration for testing."""
pass
class ContentKeyPolicyFairPlayConfiguration(ContentKeyPolicyConfiguration):
"""FairPlay DRM configuration."""
ask: str
fair_play_pfx_password: str
fair_play_pfx: str
rental_and_lease_key_type: str
rental_duration: int
offline_rental_configuration: ContentKeyPolicyFairPlayOfflineRentalConfiguration
class ContentKeyPolicyUnknownConfiguration(ContentKeyPolicyConfiguration):
"""Unknown or unsupported configuration type."""
pass
# Policy Restrictions
class ContentKeyPolicyRestriction:
"""Base class for content key policy restrictions."""
pass
class ContentKeyPolicyOpenRestriction(ContentKeyPolicyRestriction):
"""Open access without restrictions."""
pass
class ContentKeyPolicyTokenRestriction(ContentKeyPolicyRestriction):
"""Token-based access restriction."""
issuer: str
audience: str
primary_verification_key: ContentKeyPolicyRestrictionTokenKey
alternative_verification_keys: List[ContentKeyPolicyRestrictionTokenKey]
required_claims: List[ContentKeyPolicyTokenClaim]
restriction_token_type: str # ContentKeyPolicyRestrictionTokenType enum
open_id_connect_discovery_document: str
class ContentKeyPolicyUnknownRestriction(ContentKeyPolicyRestriction):
"""Unknown or unsupported restriction type."""
pass
# Token Keys and Claims
class ContentKeyPolicyRestrictionTokenKey:
"""Base class for token verification keys."""
pass
class ContentKeyPolicySymmetricTokenKey(ContentKeyPolicyRestrictionTokenKey):
"""Symmetric key for token verification."""
key_value: str
class ContentKeyPolicyRsaTokenKey(ContentKeyPolicyRestrictionTokenKey):
"""RSA public key for token verification."""
exponent: str
modulus: str
class ContentKeyPolicyX509CertificateTokenKey(ContentKeyPolicyRestrictionTokenKey):
"""X.509 certificate for token verification."""
raw_body: str
class ContentKeyPolicyTokenClaim:
"""Required claim in access tokens."""
claim_type: str
claim_value: str
# PlayReady License Configuration
class ContentKeyPolicyPlayReadyLicense:
"""PlayReady license configuration."""
allow_test_devices: bool
begin_date: str
expiration_date: str
relative_begin_date: str
relative_expiration_date: str
grace_period: str
play_right: ContentKeyPolicyPlayReadyPlayRight
license_type: str # ContentKeyPolicyPlayReadyLicenseType enum
content_key_location: ContentKeyPolicyPlayReadyContentKeyLocation
content_type: str # ContentKeyPolicyPlayReadyContentType enum
class ContentKeyPolicyPlayReadyPlayRight:
"""PlayReady play right configuration."""
first_play_expiration: str
scms_restriction: int
agc_and_color_stripe_restriction: int
explicit_analog_television_output_restriction: ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction
digital_video_only_content_restriction: bool
image_constraint_for_analog_component_video_restriction: bool
image_constraint_for_analog_computer_monitor_restriction: bool
allow_passing_video_content_to_unknown_output: str
uncompressed_digital_video_opl: int
compressed_digital_video_opl: int
analog_video_opl: int
compressed_digital_audio_opl: int
uncompressed_digital_audio_opl: int
# Content Keys Response
class ListContentKeysResponse:
"""Response containing content encryption keys."""
content_keys: List[StreamingLocatorContentKey]
class StreamingLocatorContentKey:
"""Content key for encrypted streaming."""
id: str
type: str # StreamingLocatorContentKeyType enum
label_reference_in_streaming_policy: str
value: str
policy_name: str
tracks: List[TrackSelection]from azure.mgmt.media import AzureMediaServices
from azure.mgmt.media.models import (
ContentKeyPolicy, ContentKeyPolicyOption,
ContentKeyPolicyPlayReadyConfiguration, ContentKeyPolicyTokenRestriction,
ContentKeyPolicySymmetricTokenKey, ContentKeyPolicyTokenClaim,
ContentKeyPolicyPlayReadyLicense, ContentKeyPolicyPlayReadyPlayRight,
ContentKeyPolicyRestrictionTokenType, ContentKeyPolicyPlayReadyLicenseType
)
from azure.identity import DefaultAzureCredential
import secrets
client = AzureMediaServices(
credential=DefaultAzureCredential(),
subscription_id="your-subscription-id"
)
# Generate symmetric key for token verification
token_key = secrets.token_bytes(32).hex()
# Configure token restriction
verification_key = ContentKeyPolicySymmetricTokenKey(key_value=token_key)
required_claims = [
ContentKeyPolicyTokenClaim(
claim_type="urn:microsoft:azure:mediaservices:contentkeyidentifier",
claim_value=None # Will be set automatically
)
]
token_restriction = ContentKeyPolicyTokenRestriction(
issuer="https://sts.yourdomain.com",
audience="https://media.yourdomain.com",
primary_verification_key=verification_key,
required_claims=required_claims,
restriction_token_type=ContentKeyPolicyRestrictionTokenType.JWT
)
# Configure PlayReady DRM
play_right = ContentKeyPolicyPlayReadyPlayRight(
first_play_expiration="PT24H", # 24 hours
digital_video_only_content_restriction=False,
image_constraint_for_analog_component_video_restriction=True,
image_constraint_for_analog_computer_monitor_restriction=False,
allow_passing_video_content_to_unknown_output="Allowed"
)
playready_license = ContentKeyPolicyPlayReadyLicense(
allow_test_devices=False,
relative_expiration_date="P30D", # 30 days
play_right=play_right,
license_type=ContentKeyPolicyPlayReadyLicenseType.NON_PERSISTENT
)
playready_config = ContentKeyPolicyPlayReadyConfiguration(
licenses=[playready_license]
)
# Create policy option
policy_option = ContentKeyPolicyOption(
name="TokenRestrictedPolicyOption",
configuration=playready_config,
restriction=token_restriction
)
# Create content key policy
content_key_policy = ContentKeyPolicy(
description="Token-restricted PlayReady policy",
options=[policy_option]
)
created_policy = client.content_key_policies.create_or_update(
resource_group_name="my-resource-group",
account_name="my-media-service",
content_key_policy_name="token-restricted-policy",
parameters=content_key_policy
)
print(f"Content key policy created: {created_policy.name}")
print(f"Policy ID: {created_policy.policy_id}")
print(f"Token signing key: {token_key}")from azure.mgmt.media.models import StreamingLocator
from datetime import datetime, timedelta
# Create streaming locator with content protection
protected_locator = StreamingLocator(
asset_name="encoded-asset",
streaming_policy_name="Predefined_MultiDrmCencStreaming",
default_content_key_policy_name="token-restricted-policy",
start_time=datetime.utcnow().isoformat() + "Z",
end_time=(datetime.utcnow() + timedelta(days=30)).isoformat() + "Z"
)
created_locator = client.streaming_locators.create(
resource_group_name="my-resource-group",
account_name="my-media-service",
streaming_locator_name="protected-streaming-locator",
parameters=protected_locator
)
print(f"Protected streaming locator created: {created_locator.name}")
# Get content keys
content_keys_response = client.streaming_locators.list_content_keys(
resource_group_name="my-resource-group",
account_name="my-media-service",
streaming_locator_name="protected-streaming-locator"
)
print("Content keys:")
for key in content_keys_response.content_keys:
print(f" ID: {key.id}")
print(f" Type: {key.type}")
print(f" Policy: {key.policy_name}")import jwt
import datetime
def generate_content_token(token_key: str, content_key_id: str) -> str:
"""
Generate JWT token for accessing protected content.
Parameters:
- token_key: Symmetric key used for token signing (str)
- content_key_id: Content key identifier from streaming locator (str)
Returns:
JWT token string
"""
# Token payload
payload = {
"iss": "https://sts.yourdomain.com", # Must match policy issuer
"aud": "https://media.yourdomain.com", # Must match policy audience
"exp": int((datetime.datetime.utcnow() + datetime.timedelta(hours=24)).timestamp()),
"nbf": int(datetime.datetime.utcnow().timestamp()),
"urn:microsoft:azure:mediaservices:contentkeyidentifier": content_key_id
}
# Sign token with symmetric key
token = jwt.encode(
payload,
bytes.fromhex(token_key),
algorithm="HS256"
)
return token
# Example usage
content_key_id = content_keys_response.content_keys[0].id
access_token = generate_content_token(token_key, content_key_id)
print(f"Access token: {access_token}")from azure.mgmt.media.models import (
ContentKeyPolicyWidevineConfiguration,
ContentKeyPolicyClearKeyConfiguration
)
import json
# Create policy with multiple DRM configurations
widevine_template = {
"allowed_track_types": "SD_HD",
"content_key_specs": [{
"track_type": "SD",
"security_level": 1,
"required_output_protection": {
"hdcp": "HDCP_NONE"
}
}],
"policy_overrides": {
"can_play": True,
"can_persist": False,
"can_renew": False
}
}
# PlayReady option
playready_option = ContentKeyPolicyOption(
name="PlayReadyOption",
configuration=playready_config, # From previous example
restriction=token_restriction # From previous example
)
# Widevine option
widevine_config = ContentKeyPolicyWidevineConfiguration(
widevine_template=json.dumps(widevine_template)
)
widevine_option = ContentKeyPolicyOption(
name="WidevineOption",
configuration=widevine_config,
restriction=token_restriction
)
# Clear key option for testing
clear_key_config = ContentKeyPolicyClearKeyConfiguration()
clear_key_option = ContentKeyPolicyOption(
name="ClearKeyOption",
configuration=clear_key_config,
restriction=token_restriction
)
# Multi-DRM policy
multi_drm_policy = ContentKeyPolicy(
description="Multi-DRM content protection policy",
options=[playready_option, widevine_option, clear_key_option]
)
client.content_key_policies.create_or_update(
resource_group_name="my-resource-group",
account_name="my-media-service",
content_key_policy_name="multi-drm-policy",
parameters=multi_drm_policy
)
print("Multi-DRM content key policy created")Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-mediadocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10