Skip to content
This repository has been archived by the owner on Nov 27, 2023. It is now read-only.

Commit

Permalink
Azure AD Support for Azure Media Services (#959)
Browse files Browse the repository at this point in the history
* Update AMS API Version to 2.17 + Fix integration tests

* Add AzureAD support (WIP)

* Update samples and unit test to use Azure AD Service Princial authentication

* Add User/Pass authentication + Access Token Cache

* Update README.md

* Fix typo

* Fix typo

* Remove old unit test + dead code

* Updated README document of Azure Media Services samples to include Azure AD authentication scenarios

* Fix MediaServicesSettings unit tests

* Remove group annotation

* Fix AuthenticationFilter unit tests
  • Loading branch information
marcerodriguez authored and sergey-shandar committed Nov 27, 2017
1 parent 0d3ce5b commit 498a386
Show file tree
Hide file tree
Showing 38 changed files with 1,867 additions and 753 deletions.
87 changes: 49 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Microsoft Azure tables, blobs, queues, service bus (queues and topics), service
* deployment: create, get, delete, swap, change configuration, update status, upgrade, rollback
* role instance: reboot, reimage
* REST API Version: 2011-10-01
* Media Services
* Media Services
* Connection
* Ingest asset, upload files
* Encoding / process asset, create job, job templates
Expand All @@ -51,7 +51,7 @@ Microsoft Azure tables, blobs, queues, service bus (queues and topics), service
* Live streaming: live encoding and pass-through channels, programs and all their operations
* REST API Version: 2.13


# Getting Started
## Download Source Code

Expand All @@ -63,7 +63,7 @@ cd ./azure-sdk-for-php
```

> **Note**
>
>
> The recommended way to resolve dependencies is to install them using the [Composer package manager](http://getcomposer.org).
## Install via Composer
Expand All @@ -72,9 +72,9 @@ cd ./azure-sdk-for-php

```json
{
"require": {
"require": {
"microsoft/windowsazure": "^0.5"
}
}
}
```

Expand All @@ -94,14 +94,14 @@ cd ./azure-sdk-for-php

## Getting Started

There are four basic steps that have to be performed before you can make a call to any Microsoft Azure API when using the libraries.
There are four basic steps that have to be performed before you can make a call to any Microsoft Azure API when using the libraries.

* First, include the autoloader script:

```PHP
require_once "vendor/autoload.php";
```

* Include the namespaces you are going to use.

To create any Microsoft Azure service client you need to use the **ServicesBuilder** class:
Expand All @@ -115,17 +115,17 @@ There are four basic steps that have to be performed before you can make a call
```PHP
use WindowsAzure\Common\ServiceException;
```
* To instantiate the service client you will also need a valid connection string. The format is:

* To instantiate the service client you will also need a valid connection string. The format is:

* For accessing a live storage service (tables, blobs, queues):

```
DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]
```
* For accessing the emulator storage:
```
UseDevelopmentStorage=true
```
Expand Down Expand Up @@ -170,8 +170,19 @@ There are four basic steps that have to be performed before you can make a call
* For Media Services:
```PHP
$mediaServicesRestProxy = ServicesBuilder->getInstance()->createMediaServicesService(new MediaServicesSettings([YourAccountName], [YourPrimaryOrSecondaryAccessKey]));
// 1 - Instantiate the credentials
$credentials = new AzureAdTokenCredentials(
'<tenant domain name>',
new AzureAdClientSymmetricKey('<service principal client id>', '<service principal client key>'),
AzureEnvironments::AZURE_CLOUD_ENVIRONMENT());
// 2 - Instantiate a token provider
$provider = new AzureAdTokenProvider($credentials);
// 3 - Connect to Azure Media Services
$mediaServicesRestProxy = ServicesBuilder::getInstance()->createMediaServicesService(new MediaServicesSettings('<rest api endpoint>', $provider));
```
You can find more examples for Media Services Authentication on the [examples](examples/MediaServices/) folder.
## Table Storage
Expand Down Expand Up @@ -250,9 +261,9 @@ The following are examples of common operations performed with the Blob serivce.
```PHP
// OPTIONAL: Set public access policy and metadata.
// Create container options object.
$createContainerOptions = new CreateContainerOptions();
$createContainerOptions = new CreateContainerOptions();

// Set public access policy. Possible values are
// Set public access policy. Possible values are
// PublicAccessType::CONTAINER_AND_BLOBS and PublicAccessType::BLOBS_ONLY.
// CONTAINER_AND_BLOBS: full public read access for container and blob data.
// BLOBS_ONLY: public read access for blobs. Container data not available.
Expand Down Expand Up @@ -306,7 +317,7 @@ try {
// List blobs.
$blob_list = $blobRestProxy->listBlobs("mycontainer");
$blobs = $blob_list->getBlobs();

foreach($blobs as $blob)
{
echo $blob->getName().": ".$blob->getUrl()."<br />";
Expand Down Expand Up @@ -346,7 +357,7 @@ try {
```

[Error Codes and Messages for Queues](http://msdn.microsoft.com/en-us/library/windowsazure/dd179446.aspx)


### Add a message to a queue

Expand Down Expand Up @@ -427,20 +438,20 @@ try {
```

## Service Bus Queues
The current PHP Service Bus APIs only support ACS connection strings. You need to use PowerShell to create a new ACS Service Bus namespace at the present time.
First, make sure you have Azure PowerShell installed, then in a PowerShell command prompt, run
The current PHP Service Bus APIs only support ACS connection strings. You need to use PowerShell to create a new ACS Service Bus namespace at the present time.
First, make sure you have Azure PowerShell installed, then in a PowerShell command prompt, run
```PowerShell
Add-AzureAccount # this will sign you in
New-AzureSBNamespace -CreateACSNamespace $true -Name 'mytestbusname' -Location 'West US' -NamespaceType 'Messaging'
```
If it is sucessful, you will get the connection string in the PowerShell output. If you get connection errors with it and the conection string looks like Endpoint=sb://..., change it to **Endpoint=https://...**

### Create a Queue

```PHP
try {
$queueInfo = new QueueInfo("myqueue");

// Create queue.
$serviceBusRestProxy->createQueue($queueInfo);
} catch(ServiceException $e){
Expand Down Expand Up @@ -483,14 +494,14 @@ try {
// Set the receive mode to PeekLock (default is ReceiveAndDelete).
$options = new ReceiveMessageOptions();
$options->setPeekLock(true);

// Receive message.
$message = $serviceBusRestProxy->receiveQueueMessage("myqueue", $options);
echo "Body: ".$message->getBody()."<br />";
echo "MessageID: ".$message->getMessageId()."<br />";

// *** Process message here ***

// Delete message.
$serviceBusRestProxy->deleteMessage($message);
} catch(ServiceException $e){
Expand All @@ -505,7 +516,7 @@ try {
### Create a Topic

```PHP
try {
try {
// Create topic.
$topicInfo = new TopicInfo("mytopic");
$serviceBusRestProxy->createTopic($topicInfo);
Expand Down Expand Up @@ -553,7 +564,7 @@ try {

The primary way to receive messages from a subscription is to use a **ServiceBusRestProxy->receiveSubscriptionMessage** method. Received messages can work in two different modes: **ReceiveAndDelete** (the default) and **PeekLock** similarly to Service Bus Queues.

The example below demonstrates how a message can be received and processed using **ReceiveAndDelete** mode (the default mode).
The example below demonstrates how a message can be received and processed using **ReceiveAndDelete** mode (the default mode).

```PHP
try {
Expand All @@ -562,8 +573,8 @@ try {
$options->setReceiveAndDelete();

// Get message.
$message = $serviceBusRestProxy->receiveSubscriptionMessage("mytopic",
"mysubscription",
$message = $serviceBusRestProxy->receiveSubscriptionMessage("mytopic",
"mysubscription",
$options);
echo "Body: ".$message->getBody()."<br />";
echo "MessageID: ".$message->getMessageId()."<br />";
Expand All @@ -578,18 +589,18 @@ try {

### Set-up certificates

You need to create two certificates, one for the server (a .cer file) and one for the client (a .pem file). To create the .pem file using [OpenSSL](http://www.openssl.org), execute this:
You need to create two certificates, one for the server (a .cer file) and one for the client (a .pem file). To create the .pem file using [OpenSSL](http://www.openssl.org), execute this:
```
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
```
To create the .cer certificate, execute this:
To create the .cer certificate, execute this:
```
openssl x509 -inform pem -in mycert.pem -outform der -out mycert.cer
```

### List Available Locations

```PHP
```PHP
$serviceManagementRestProxy->listLocations();
$locations = $result->getLocations();
foreach($locations as $location){
Expand All @@ -608,11 +619,11 @@ $options = new CreateStorageServiceOptions();
$options->setLocation('West US');

$result = $serviceManagementRestProxy->createStorageService($name, $label, $options);
```
```

### Create a Cloud Service

A cloud service is also known as a hosted service (from earlier versions of Microsoft Azure). The **createHostedServices** method allows you to create a new hosted service by providing a hosted service name (which must be unique in Microsoft Azure), a label (the base 64-endcoded hosted service name), and a **CreateServiceOptions** object which allows you to set the location *or* the affinity group for your service.
A cloud service is also known as a hosted service (from earlier versions of Microsoft Azure). The **createHostedServices** method allows you to create a new hosted service by providing a hosted service name (which must be unique in Microsoft Azure), a label (the base 64-endcoded hosted service name), and a **CreateServiceOptions** object which allows you to set the location *or* the affinity group for your service.

```PHP
$name = "myhostedservice";
Expand Down Expand Up @@ -648,7 +659,7 @@ echo "Operation status: ".$status->getStatus()."<br />";
```

## Media Services

### Create new asset with file

To create an asset with a file you need to create an empty asset, create access policy with write permission, create a locator joining your asset and access policy, perform actual upload and generate file info.
Expand Down Expand Up @@ -713,11 +724,11 @@ $streamingUrl = $originLocator->getPath() . '[Manifest file name]' . "/manifest"

### Manage media services entities

Media services CRUD operations are performed through media services rest proxy class. It has methods like “createAsset”, “createLocator”, “createJob” and etc. for entities creations.
Media services CRUD operations are performed through media services rest proxy class. It has methods like “createAsset”, “createLocator”, “createJob” and etc. for entities creations.

To retrieve all entities list you may use methods “getAssetList”, “getAccessPolicyList”, “getLocatorList”, “getJobList” and etc. For getting single entity data use methods “getAsset”, “getJob”, “getTask” and etc. passing the entity identifier or entity data model object with non-empty identifier as a parameter.
To retrieve all entities list you may use methods “getAssetList”, “getAccessPolicyList”, “getLocatorList”, “getJobList” and etc. For getting single entity data use methods “getAsset”, “getJob”, “getTask” and etc. passing the entity identifier or entity data model object with non-empty identifier as a parameter.

Update entities with methods like “updateLocator”, “updateAsset”, “updateAssetFile” and etc. passing the entity data model object as a parameter. It is important to have valid entity identifier specified in data model object.
Update entities with methods like “updateLocator”, “updateAsset”, “updateAssetFile” and etc. passing the entity data model object as a parameter. It is important to have valid entity identifier specified in data model object.

Erase entities with methods like “deleteAsset”, “deleteAccessPolicy”, “deleteJob” and etc. passing the entity identifier or entity data model object with non-empty identifier as a parameter.

Expand Down
5 changes: 4 additions & 1 deletion examples/MediaServices/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
This folder contains the following Azure Media Service PHP SDK samples:
This folder contains the following Azure Media Services PHP SDK samples:

* vodworkflow_aes.php: End-to-end VOD workflow that applies AES content protection.
* vodworkflow_drm_playready_widevine.php: End-to-end VOD workflow that applies DRM (PlayReady + Widevine) content protection.
* vodworkflow_drm_fairplay.php: End-to-end VOD workflow that applies DRM (FairPlay) content protection.
* scale_encoding_units.php: Scales the encoding reserved units.
* analyticsworkflow_indexer.php: End-to-end analitycs workflow to index a media file.
* liveworkflow_features.php: End-to-end live event workflow with configuration options to cover multiple scenarios.
* azuread_userpass.php: Azure AD authentication with user credentials (username/password).
* azuread_symmetrickey.php: Azure AD authentication with service principal (client symmetric key).
* azuread_asymmetrickey: Azure AD authentication with service principal (client certificate).
* userconfig.php: Common file used to store the Azure Media Services account credentials to execute all the samples.
13 changes: 10 additions & 3 deletions examples/MediaServices/analyticsworkflow_indexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\Internal\MediaServicesSettings;
use WindowsAzure\MediaServices\MediaServicesRestProxy;
use WindowsAzure\MediaServices\Authentication\AzureAdTokenCredentials;
use WindowsAzure\MediaServices\Authentication\AzureAdClientSymmetricKey;
use WindowsAzure\MediaServices\Authentication\AzureAdTokenProvider;
use WindowsAzure\MediaServices\Authentication\AzureEnvironments;
use WindowsAzure\MediaServices\Models\Asset;
use WindowsAzure\MediaServices\Models\AccessPolicy;
use WindowsAzure\MediaServices\Models\Locator;
Expand All @@ -51,9 +55,12 @@

echo "Azure SDK for PHP - Media Analytics Sample (Indexer)".PHP_EOL;

// 0 - Set up the MediaServicesService object to call into the Media Services REST API.
$restProxy = ServicesBuilder::getInstance()->createMediaServicesService(
new MediaServicesSettings($account, $secret));
// 0 - Instantiate the credentials, the token provider and connect to Azure Media Services
$credentials = new AzureAdTokenCredentials(
$tenant, new AzureAdClientSymmetricKey($clientId, $clientKey),
AzureEnvironments::AZURE_CLOUD_ENVIRONMENT());
$provider = new AzureAdTokenProvider($credentials);
$restProxy = ServicesBuilder::getInstance()->createMediaServicesService(new MediaServicesSettings($restApiEndpoint, $provider));

// 1 - Upload the mezzanine
$sourceAsset = uploadFileAndCreateAsset($restProxy, $mediaFileName);
Expand Down
66 changes: 66 additions & 0 deletions examples/MediaServices/azuread_asymmetrickey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

/**
* LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* PHP version 5
*
* @category Microsoft
*
* @author Azure PHP SDK <[email protected]>
* @copyright 2012 Microsoft Corporation
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
*
* @link https://github.com/windowsazure/azure-sdk-for-php
*/
require_once __DIR__.'/../../vendor/autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\Internal\MediaServicesSettings;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\MediaServices\MediaServicesRestProxy;
use WindowsAzure\MediaServices\Authentication\AzureAdTokenCredentials;
use WindowsAzure\MediaServices\Authentication\AzureAdClientAsymmetricKey;
use WindowsAzure\MediaServices\Authentication\AzureAdTokenProvider;
use WindowsAzure\MediaServices\Authentication\AzureEnvironments;
use WindowsAzure\MediaServices\Models\Asset;

// read user settings from config
include_once 'userconfig.php';

echo "Azure SDK for PHP - AzureAD Asymmetric Key Authentication Sample".PHP_EOL;

// 0 - Open the certificate file
if ((!$cert_store = file_get_contents($pfxFileName)) ||
(!openssl_pkcs12_read($cert_store, $cert_info, $pfxPassword))) {
echo "Error: Unable to read the cert file\n";
exit;
}

// 1 - Instantiate the credentials
$credentials = new AzureAdTokenCredentials(
$tenant,
new AzureAdClientAsymmetricKey($clientId, $cert_info),
AzureEnvironments::AZURE_CLOUD_ENVIRONMENT());

// 2 - Instantiate a token provider
$provider = new AzureAdTokenProvider($credentials);

// 3 - Connect to Azure Media Services
$restProxy = ServicesBuilder::getInstance()->createMediaServicesService(new MediaServicesSettings($restApiEndpoint, $provider));

// 4 - List assets (sample operation)
print('Listing Assets:' . PHP_EOL);
foreach($restProxy->getAssetList() as $asset)
{
print('Asset Id=' . $asset->getId() . ' Name=' . $asset->getName() . PHP_EOL);
}
Loading

0 comments on commit 498a386

Please sign in to comment.