使用 Azure AD 身份验证可通过 .NET 访问 Azure 媒体服务 APIUse Azure AD authentication to access Azure Media Services API with .NET

Note

不会向媒体服务 v2 添加任何新特性或新功能。No new features or functionality are being added to Media Services v2.
查看最新版本:媒体服务 v3Check out the latest version, Media Services v3. 另请参阅从 v2 到 v3 的迁移指南Also, see migration guidance from v2 to v3

从 windowsazure.mediaservices 4.0.0.4 开始,Azure 媒体服务支持基于 Azure Active Directory (Azure AD) 的身份验证。Starting with windowsazure.mediaservices 4.0.0.4, Azure Media Services supports authentication based on Azure Active Directory (Azure AD). 本主题介绍了如何使用 Azure AD 身份验证通过 Microsoft .NET 访问 Azure 媒体服务 API。This topic shows you how to use Azure AD authentication to access Azure Media Services API with Microsoft .NET.

必备条件Prerequisites

通过 Azure 媒体服务使用 Azure AD 身份验证时,可以通过以下两种方式之一进行身份验证:When you're using Azure AD authentication with Azure Media Services, you can authenticate in one of two ways:

  • 用户身份验证:对使用应用程序与 Azure 媒体服务资源进行交互的人员执行身份验证。User authentication authenticates a person who is using the app to interact with Azure Media Services resources. 交互式应用程序应先提示用户输入凭据。The interactive application should first prompt the user for credentials. 举个例子,授权用户用来监视编码作业或实时流式处理的管理控制台应用程序。An example is a management console app that's used by authorized users to monitor encoding jobs or live streaming.
  • 服务主体身份验证:对服务进行身份验证。Service principal authentication authenticates a service. 通常使用此身份验证方法的应用程序是运行守护程序服务、中间层服务或计划作业的应用:如 Web 应用、函数应用、逻辑应用、 API 或微服务。Applications that commonly use this authentication method are apps that run daemon services, middle-tier services, or scheduled jobs, such as web apps, function apps, logic apps, APIs, or microservices.

Important

Azure 媒体服务目前支持 Azure 访问控制服务身份验证模型。Azure Media Service currently supports an Azure Access Control Service authentication model. 但是,访问控制授权将于 2018 年 6 月 22 日弃用。However, Access Control authorization is going to be deprecated on June 22, 2018. 建议尽快迁移到 Azure Active Directory 身份验证模型。We recommend that you migrate to an Azure Active Directory authentication model as soon as possible.

获取 Azure AD 访问令牌Get an Azure AD access token

要通过 Azure AD 身份验证连接到 Azure 媒体服务 API,客户端应用程序需要请求 Azure AD 访问令牌。To connect to the Azure Media Services API with Azure AD authentication, the client app needs to request an Azure AD access token. 使用媒体服务 .NET 客户端 SDK 时,有关如何获取 Azure AD 访问令牌的诸多详细信息将在 AzureAdTokenProviderAzureAdTokenCredentials 类中进行包装和简化。When you use the Media Services .NET client SDK, many of the details about how to acquire an Azure AD access token are wrapped and simplified for you in the AzureAdTokenProvider and AzureAdTokenCredentials classes.

例如,无需提供 Azure AD 主管机构、媒体服务资源 URI 或本机 Azure AD 应用程序详细信息。For example, you don't need to provide the Azure AD authority, Media Services resource URI, or native Azure AD application details. 这些是已由 Azure AD 访问令牌提供程序类配置的已知值。These are well-known values that are already configured by the Azure AD access token provider class.

如果不使用 Azure 媒体服务 .NET SDK,我们建议使用 Azure AD 身份验证库If you are not using Azure Media Service .NET SDK, we recommend that you use the Azure AD Authentication Library. 要获取用于 Azure AD 身份验证库所需的参数的值,请参阅使用 Azure 门户访问 Azure AD 身份验证设置To get values for the parameters that you need to use with Azure AD Authentication Library, see Use the Azure portal to access Azure AD authentication settings.

还可以选择将 AzureAdTokenProvider 的默认实现方式替换为你自己的实现方式。You also have the option of replacing the default implementation of the AzureAdTokenProvider with your own implementation.

安装和配置 Azure 媒体服务 .NET SDKInstall and configure Azure Media Services .NET SDK

Note

要将 Azure AD 身份验证用于媒体服务 .NET SDK,需要有最新的 NuGet 程序包。To use Azure AD authentication with the Media Services .NET SDK, you need to have the latest NuGet package. 此外,将引用添加到 Microsoft.IdentityModel.Clients.ActiveDirectory 程序集。Also, add a reference to the Microsoft.IdentityModel.Clients.ActiveDirectory assembly. 如果你使用的是现有应用,则加入 Microsoft.WindowsAzure.MediaServices.Client.Common.Authentication.dll 程序集。If you are using an existing app, include the Microsoft.WindowsAzure.MediaServices.Client.Common.Authentication.dll assembly.

  1. 在 Visual Studio 中创建新的 C# 控制台应用程序。Create a new C# console application in Visual Studio.

  2. 使用 windowsazure.mediaservices NuGet 程序包安装 Azure 媒体服务 .NET SDK 。Use the windowsazure.mediaservices NuGet package to install Azure Media Services .NET SDK.

    若要使用 NuGet 添加引用,请执行以下步骤:在“解决方案资源管理器” 中,右键单击项目名称,然后选择“管理 NuGet 程序包” 。To add references by using NuGet, take the following steps: in Solution Explorer, right-click the project name, and then select Manage NuGet packages. 然后,搜索 windowsazure.mediaservices ,并选择“安装” 。Then, search for windowsazure.mediaservices and select Install.

    -或--or-

    在 Visual Studio 的程序包管理器控制台 中运行以下命令。Run the following command in Package Manager Console in Visual Studio.

     Install-Package windowsazure.mediaservices -Version 4.0.0.4
    
  3. 将 using 添加到源代码中。Add using to your source code.

     using Microsoft.WindowsAzure.MediaServices.Client; 
    

使用用户身份验证Use user authentication

若要通过使用用户身份验证选项连接到 Azure 媒体服务 API,客户端应用程序需要使用以下参数请求 Azure AD 令牌:To connect to the Azure Media Service API with the user authentication option, the client app needs to request an Azure AD token by using the following parameters:

  • Azure AD 租户终结点。Azure AD tenant endpoint. 可以在 Azure 门户中检索租户信息。The tenant information can be retrieved from the Azure portal. 将鼠标悬停在右上角的已登录用户上。Hover over the signed-in user in the upper-right corner.
  • 媒体服务资源 URI。Media Services resource URI.
  • 媒体服务(本机)应用程序客户端 ID。Media Services (native) application client ID.
  • 媒体服务(本机)应用程序重定向 URI。Media Services (native) application redirect URI.

这些参数的值可在 AzureEnvironments.AzureChinaCloudEnvironment 中找到。The values for these parameters can be found in AzureEnvironments.AzureChinaCloudEnvironment. AzureEnvironments.AzureChinaCloudEnvironment 常量是 .NET SDK 中的一个帮助程序,可以为公共 Azure 数据中心获取正确的环境变量设置。The AzureEnvironments.AzureChinaCloudEnvironment constant is a helper in the .NET SDK to get the right environment variable settings for a public Azure Data Center.

它包含预定义的环境设置,从而仅允许访问公共数据中心中的媒体服务。It contains pre-defined environment settings for accessing Media Services in the public data centers only. 在中国云区域,可以使用 AzureChinaCloudEnvironmentFor China cloud regions, you can use AzureChinaCloudEnvironment .

以下示例代码创建一个令牌:The following code example creates a token:

var tokenCredentials = new AzureAdTokenCredentials("microsoft.partner.onmschina.cn", AzureEnvironments.AzureChinaCloudEnvironment);
var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

若要开始针对媒体服务编程,需要创建一个代表服务器上下文的 CloudMediaContext 实例。To start programming against Media Services, you need to create a CloudMediaContext instance that represents the server context. CloudMediaContext 包括对各种重要集合的引用,这些集合包括作业、资产、文件、访问策略和定位符。The CloudMediaContext includes references to important collections including jobs, assets, files, access policies, and locators.

此外,还需要将媒体 REST 服务的资源 URI 传递到 CloudMediaContext 构造函数。You also need to pass the resource URI for Media REST Services to the CloudMediaContext constructor. 要获取媒体 REST 服务的资源 URI,请登录到 Azure 门户,选择 Azure 媒体服务帐户,然后依次选择“API 访问权限” 、“通过用户身份验证连接到 Azure 媒体服务” 。To get the resource URI for Media REST Services, sign in to the Azure portal, select your Azure Media Services account, select API access, and then select Connect to Azure Media Services with user authentication.

下面的代码示例创建 CloudMediaContext 实例:The following code example creates a CloudMediaContext instance:

CloudMediaContext context = new CloudMediaContext(new Uri("YOUR REST API ENDPOINT HERE"), tokenProvider);

以下示例介绍如何创建 Azure AD 令牌和上下文:The following example shows how to create the Azure AD token and the context:

namespace AzureADAuthSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specify your Azure AD tenant domain, for example "microsoft.partner.onmschina.cn".
            var tokenCredentials = new AzureAdTokenCredentials("{YOUR Azure AD TENANT DOMAIN HERE}", AzureEnvironments.AzureChinaCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            // Specify your REST API endpoint, for example "https://accountname.restv2.chinaeast.media.chinacloudapi.cn/API".
            CloudMediaContext context = new CloudMediaContext(new Uri("YOUR REST API ENDPOINT HERE"), tokenProvider);

            var assets = context.Assets;
            foreach (var a in assets)
            {
                Console.WriteLine(a.Name);
            }
        }

    }
}

Note

如果收到异常,指示“远程服务器返回了一个错误: (401)未授权”,请参阅使用 Azure AD身份验证访问 Azure 媒体服务 API 概述的访问控制部分。If you get an exception that says "The remote server returned an error: (401) Unauthorized," see the Access control section of Accessing Azure Media Services API with Azure AD authentication overview.

使用服务主体身份验证Use service principal authentication

若要通过服务主体选项连接到 Azure 媒体服务 API,中间层应用程序(Web API 或 Web 应用程序)需要使用以下参数请求 Azure AD 令牌:To connect to the Azure Media Services API with the service principal option, your middle-tier app (web API or web application) needs to requests an Azure AD token with the following parameters:

  • Azure AD 租户终结点。Azure AD tenant endpoint. 可以在 Azure 门户中检索租户信息。The tenant information can be retrieved from the Azure portal. 将鼠标悬停在右上角的已登录用户上。Hover over the signed-in user in the upper-right corner.
  • 媒体服务资源 URI。Media Services resource URI.
  • Azure AD 应用程序值:客户端 ID 和客户端密码 。Azure AD application values: the Client ID and Client secret.

客户端 ID 和客户端密码 参数的值都可以在 Azure 门户中找到。The values for the Client ID and Client secret parameters can be found in the Azure portal. 有关详细信息,请参阅使用 Azure 门户进行 Azure AD 身份验证入门For more information, see Getting started with Azure AD authentication using the Azure portal.

以下代码示例使用将 AzureAdClientSymmetricKey 作为参数的 AzureAdTokenCredentials 构造函数创建令牌:The following code example creates a token by using the AzureAdTokenCredentials constructor that takes AzureAdClientSymmetricKey as a parameter:

var tokenCredentials = new AzureAdTokenCredentials("{YOUR Azure AD TENANT DOMAIN HERE}", 
                            new AzureAdClientSymmetricKey("{YOUR CLIENT ID HERE}", "{YOUR CLIENT SECRET}"), 
                            AzureEnvironments.AzureChinaCloudEnvironment);

var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

你还可以指定将 AzureAdClientCertificate 作为参数的 AzureAdTokenCredentials 构造函数。You can also specify the AzureAdTokenCredentials constructor that takes AzureAdClientCertificate as a parameter.

有关如何在表单中创建和配置可由 Azure AD 使用的证书的说明,请参阅使用证书在守护程序应用中对 Azure AD 进行身份验证 - 手动配置步骤For instructions about how to create and configure a certificate in a form that can be used by Azure AD, see Authenticating to Azure AD in daemon apps with certificates - manual configuration steps.

var tokenCredentials = new AzureAdTokenCredentials("{YOUR Azure AD TENANT DOMAIN HERE}", 
                            new AzureAdClientCertificate("{YOUR CLIENT ID HERE}", "{YOUR CLIENT CERTIFICATE THUMBPRINT}"), 
                            AzureEnvironments.AzureChinaCloudEnvironment);

若要开始针对媒体服务编程,需要创建一个代表服务器上下文的 CloudMediaContext 实例。To start programming against Media Services, you need to create a CloudMediaContext instance that represents the server context. 此外,还需要将媒体 REST 服务的资源 URI 传递到 CloudMediaContext 构造函数。You also need to pass the resource URI for Media REST Services to the CloudMediaContext constructor. 你也可以从 Azure 门户获取媒体 REST 服务的资源 URI 值 。You can get the resource URI for Media REST Services value from the Azure portal as well.

下面的代码示例创建 CloudMediaContext 实例:The following code example creates a CloudMediaContext instance:

CloudMediaContext context = new CloudMediaContext(new Uri("YOUR REST API ENDPOINT HERE"), tokenProvider);

以下示例介绍如何创建 Azure AD 令牌和上下文:The following example shows how to create the Azure AD token and the context:

namespace AzureADAuthSample
{

    class Program
    {
        static void Main(string[] args)
        {
            var tokenCredentials = new AzureAdTokenCredentials("{YOUR Azure AD TENANT DOMAIN HERE}", 
                                        new AzureAdClientSymmetricKey("{YOUR CLIENT ID HERE}", "{YOUR CLIENT SECRET}"), 
                                        AzureEnvironments.AzureChinaCloudEnvironment);
        
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            // Specify your REST API endpoint, for example "https://accountname.restv2.chinaeast.media.chinacloudapi.cn/API".       
            CloudMediaContext context = new CloudMediaContext(new Uri("YOUR REST API ENDPOINT HERE"), tokenProvider);

            var assets = context.Assets;
            foreach (var a in assets)
            {
                Console.WriteLine(a.Name);
            }

            Console.ReadLine();
        }

    }
}

后续步骤Next steps

开始将文件上传到帐户Get started with uploading files to your account.