如何使用最新的 SDK 创建或更新证书

huangapple go评论68阅读模式
英文:

How to create or update a certificate using the latest SDK

问题

有人知道与此REST API等效的SDK是什么吗?不幸的是,SDK文档非常不完善,我挖了整整两天之后,终于不得不询问。

我之前的研究和我尝试过的东西在这里有详细说明。

英文:

Does anyone know what the SDK equivalent to this REST API is? Unfortunately, the SDK is so poorly documented that—after two full days of digging—I finally have to ask.

My prior research and things I've tried are detailed here.

答案1

得分: 1

以下是您提供的文本的翻译:

若要使用 SDK 创建或更新证书,您可以参考此GitHub示例Latest Azure.ResourceManager.AppService .Net示例

来自上述GitHub示例的代码:

// 创建或更新证书
[NUnit.Framework.Test]
[NUnit.Framework.Ignore("仅验证示例是否构建")]
public async Task CreateOrUpdate_CreateOrUpdateCertificate()
{
    // 从示例定义生成:specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/CreateOrUpdateCertificate.json
    // 此示例仅显示了“Certificates_CreateOrUpdate”操作的用法,对于依赖资源,它们必须单独创建。

    // 获取您的 Azure 访问令牌,有关 Azure SDK 如何获取您的访问令牌的详细信息,请参阅
    // https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
    TokenCredential cred = new DefaultAzureCredential();
    // 验证您的客户端
    ArmClient client = new ArmClient(cred);

    // 此示例假定您已在 Azure 上创建了此 ResourceGroupResource
    // 有关创建 ResourceGroupResource 的详细信息,请参阅 ResourceGroupResource 文档
    string subscriptionId = "xxxxsubidxxxx";
    string resourceGroupName = "rgname";
    ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
    ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);

    // 获取此 AppCertificateResource 的集合
    AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();

    // 调用操作
    string name = "certname";
    AppCertificateData data = new AppCertificateData(new AzureLocation("East US"))
    {
        Password = "<password>",
        HostNames = { "ServerCert" },
    };
    ArmOperation<AppCertificateResource> lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, name, data);
    AppCertificateResource result = lro.Value;

    // 变量 result 是一个资源,您也可以在此实例上调用其他操作
    // 但只是为了演示,我们从此资源实例中获取其数据
    AppCertificateData resourceData = result.Data;
    // 仅用于演示,我们打印出其 ID
    Console.WriteLine($"成功的 ID: {resourceData.Id}");
}

完整的代码来管理应用服务的证书:

using System;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService;
using Azure.ResourceManager.Resources;
using NUnit;

namespace Azure.ResourceManager.AppService.Samples
{
    public partial class Sample_AppCertificateCollection
    {
        static void Main(string[] args)
        {
        }
        // 按资源组列出证书
        [NUnit.Framework.Test]
        [NUnit.Framework.Ignore("仅验证示例是否构建")]
        public async Task GetAll_ListCertificatesByResourceGroup()
        {
            // 从示例定义生成:specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/ListCertificatesByResourceGroup.json
            // 此示例仅显示了“Certificates_ListByResourceGroup”操作的用法,对于依赖资源,它们必须单独创建。

            // 获取您的 Azure 访问令牌,有关 Azure SDK 如何获取您的访问令牌的详细信息,请参阅
            // https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
            TokenCredential cred = new DefaultAzureCredential();
            // 验证您的客户端
            ArmClient client = new ArmClient(cred);

            // 此示例假定您已在 Azure 上创建了此 ResourceGroupResource
            // 有关创建 ResourceGroupResource 的详细信息,请参阅 ResourceGroupResource 文档
            string subscriptionId = "0151c365-f598-44d6-b4fd-e2b6e97cb2a7";
            string resourceGroupName = "siliconrg";
            ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
            ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);

            // 获取此 AppCertificateResource 的集合
            AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();

            // 调用操作并遍历结果
            await foreach (AppCertificateResource item in collection.GetAllAsync())
            {
                // 变量 item 是一个资源,您也可以在此实例上调用其他操作
                // 但只是为了演示,我们从此资源实例中获取其数据
                AppCertificateData resourceData = item.Data;
                // 仅用于演示,我们打印出其 ID
                Console.WriteLine($"成功的 ID: {resourceData.Id}");
            }

            Console.WriteLine($"成功");
        }

        // 获取证书
        [NUnit.Framework.Test]
        [NUnit.Framework.Ignore("仅验证示例是否构建")]
        public async Task Get_GetCertificate()
        {
            // 从示例定义生成:specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/GetCertificate.json
            // 此示例仅显示了“Certificates_Get”操作的用法,对于依赖资源,它们必须单独创建。

            // 获取您的 Azure 访问令牌,有关 Azure SDK 如何获取您的访问令牌的详细信息,请参阅
            // https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
            TokenCredential cred = new DefaultAzureCredential();
            // 验证您的客户端
            ArmClient client = new ArmClient(cred);

            // 此示例假定您已在 Azure 上创建了此 ResourceGroupResource
            // 有关创建 ResourceGroupResource 的详细信息,请参阅 ResourceGroupResource 文档
            string subscriptionId = "0151c365-f598-44d6-b4fd-e2b6e97cb2a7";
            string resourceGroupName = "siliconrg";
            ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);


<details>
<summary>英文:</summary>

In order to Create or Update the Certificate with SDK you can refer this [**Github sample**](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/websites/Azure.ResourceManager.AppService/samples/Generated/Samples/Sample_AppCertificateCollection.cs) of ***Latest Azure.ResourceManager.AppService .Net sample***.

Code from the [github sample](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/websites/Azure.ResourceManager.AppService/samples/Generated/Samples/Sample_AppCertificateCollection.cs) above:-

&gt; ```csharp
&gt; 
&gt; // Create Or Update Certificate
&gt;         [NUnit.Framework.Test]
&gt;         [NUnit.Framework.Ignore(&quot;Only verifying that the sample builds&quot;)]
&gt;         public async Task CreateOrUpdate_CreateOrUpdateCertificate()
&gt;         {
&gt;             // Generated from example definition: specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/CreateOrUpdateCertificate.json
&gt;             // this example is just showing the usage of &quot;Certificates_CreateOrUpdate&quot; operation, for the dependent resources,
&gt; they will have to be created separately.
&gt; 
&gt;             // get your azure access token, for more details of how Azure SDK get your access token, please refer to
&gt; https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
&gt;             TokenCredential cred = new DefaultAzureCredential();
&gt;             // authenticate your client
&gt;             ArmClient client = new ArmClient(cred);
&gt; 
&gt;             // this example assumes you already have this ResourceGroupResource created on azure
&gt;             // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
&gt;             string subscriptionId = &quot;xxxxsubidxxxx&quot;;
&gt;             string resourceGroupName = &quot;rgname&quot;;
&gt;             ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId,
&gt; resourceGroupName);
&gt;             ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
&gt; 
&gt;             // get the collection of this AppCertificateResource
&gt;             AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();
&gt; 
&gt;             // invoke the operation
&gt;             string name = &quot;certname&quot;;
&gt;             AppCertificateData data = new AppCertificateData(new AzureLocation(&quot;East US&quot;))
&gt;             {
&gt;                 Password = &quot;&lt;password&gt;&quot;,
&gt;                 HostNames = { &quot;ServerCert&quot; },
&gt;             };
&gt;             ArmOperation&lt;AppCertificateResource&gt; lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, name, data);
&gt;             AppCertificateResource result = lro.Value;
&gt; 
&gt;             // the variable result is a resource, you could call other operations on this instance as well
&gt;             // but just for demo, we get its data from this resource instance
&gt;             AppCertificateData resourceData = result.Data;
&gt;             // for demo we just print out the id
&gt;             Console.WriteLine($&quot;Succeeded on id: {resourceData.Id}&quot;);
&gt;         }
&gt;     } 
&gt;     }
&gt; 
&gt; ```

Complete code to manage Certificates of App Service:-

&gt; ```csharp using System; using System.Threading.Tasks; using Azure;
&gt; using Azure.Core; using Azure.Identity; using Azure.ResourceManager;
&gt; using Azure.ResourceManager.AppService; using
&gt; Azure.ResourceManager.Resources; using NUnit;
&gt; 
&gt; 
&gt; 
&gt; namespace Azure.ResourceManager.AppService.Samples {
&gt;     public partial class Sample_AppCertificateCollection
&gt;     {
&gt;         static void Main(string[] args)
&gt;         {
&gt;         }
&gt;         // List Certificates by resource group
&gt;         [NUnit.Framework.Test]
&gt;         [NUnit.Framework.Ignore(&quot;Only verifying that the sample builds&quot;)]
&gt;         public async Task GetAll_ListCertificatesByResourceGroup()
&gt;         {
&gt;             // Generated from example definition: specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/ListCertificatesByResourceGroup.json
&gt;             // this example is just showing the usage of &quot;Certificates_ListByResourceGroup&quot; operation, for the dependent
&gt; resources, they will have to be created separately.
&gt; 
&gt;             // get your azure access token, for more details of how Azure SDK get your access token, please refer to
&gt; https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
&gt;             TokenCredential cred = new DefaultAzureCredential();
&gt;             // authenticate your client
&gt;             ArmClient client = new ArmClient(cred);
&gt; 
&gt;             // this example assumes you already have this ResourceGroupResource created on azure
&gt;             // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
&gt;             string subscriptionId = &quot;0151c365-f598-44d6-b4fd-e2b6e97cb2a7&quot;;
&gt;             string resourceGroupName = &quot;siliconrg&quot;;
&gt;             ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId,
&gt; resourceGroupName);
&gt;             ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
&gt; 
&gt;             // get the collection of this AppCertificateResource
&gt;             AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();
&gt; 
&gt;             // invoke the operation and iterate over the result
&gt;             await foreach (AppCertificateResource item in collection.GetAllAsync())
&gt;             {
&gt;                 // the variable item is a resource, you could call other operations on this instance as well
&gt;                 // but just for demo, we get its data from this resource instance
&gt;                 AppCertificateData resourceData = item.Data;
&gt;                 // for demo we just print out the id
&gt;                 Console.WriteLine($&quot;Succeeded on id: {resourceData.Id}&quot;);
&gt;             }
&gt; 
&gt;             Console.WriteLine($&quot;Succeeded&quot;);
&gt;         }
&gt; 
&gt;         // Get Certificate
&gt;         [NUnit.Framework.Test]
&gt;         [NUnit.Framework.Ignore(&quot;Only verifying that the sample builds&quot;)]
&gt;         public async Task Get_GetCertificate()
&gt;         {
&gt;             // Generated from example definition: specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/GetCertificate.json
&gt;             // this example is just showing the usage of &quot;Certificates_Get&quot; operation, for the dependent resources, they will
&gt; have to be created separately.
&gt; 
&gt;             // get your azure access token, for more details of how Azure SDK get your access token, please refer to
&gt; https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
&gt;             TokenCredential cred = new DefaultAzureCredential();
&gt;             // authenticate your client
&gt;             ArmClient client = new ArmClient(cred);
&gt; 
&gt;             // this example assumes you already have this ResourceGroupResource created on azure
&gt;             // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
&gt;             string subscriptionId = &quot;0151c365-f598-44d6-b4fd-e2b6e97cb2a7&quot;;
&gt;             string resourceGroupName = &quot;siliconrg&quot;;
&gt;             ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId,
&gt; resourceGroupName);
&gt;             ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
&gt; 
&gt;             // get the collection of this AppCertificateResource
&gt;             AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();
&gt; 
&gt;             // invoke the operation
&gt;             string name = &quot;certsilicon&quot;;
&gt;             AppCertificateResource result = await collection.GetAsync(name);
&gt; 
&gt;             // the variable result is a resource, you could call other operations on this instance as well
&gt;             // but just for demo, we get its data from this resource instance
&gt;             AppCertificateData resourceData = result.Data;
&gt;             // for demo we just print out the id
&gt;             Console.WriteLine($&quot;Succeeded on id: {resourceData.Id}&quot;);
&gt;         }
&gt; 
&gt;         // Get Certificate
&gt;         [NUnit.Framework.Test]
&gt;         [NUnit.Framework.Ignore(&quot;Only verifying that the sample builds&quot;)]
&gt;         public async Task Exists_GetCertificate()
&gt;         {
&gt;             // Generated from example definition: specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/GetCertificate.json
&gt;             // this example is just showing the usage of &quot;Certificates_Get&quot; operation, for the dependent resources, they will
&gt; have to be created separately.
&gt; 
&gt;             // get your azure access token, for more details of how Azure SDK get your access token, please refer to
&gt; https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
&gt;             TokenCredential cred = new DefaultAzureCredential();
&gt;             // authenticate your client
&gt;             ArmClient client = new ArmClient(cred);
&gt; 
&gt;             // this example assumes you already have this ResourceGroupResource created on azure
&gt;             // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
&gt;             string subscriptionId = &quot;0151c365-f598-44d6-b4fd-e2b6e97cb2a7&quot;;
&gt;             string resourceGroupName = &quot;siliconrg&quot;;
&gt;             ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId,
&gt; resourceGroupName);
&gt;             ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
&gt; 
&gt;             // get the collection of this AppCertificateResource
&gt;             AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();
&gt; 
&gt;             // invoke the operation
&gt;             string name = &quot;certsilicon&quot;;
&gt;             bool result = await collection.ExistsAsync(name);
&gt; 
&gt;             Console.WriteLine($&quot;Succeeded: {result}&quot;);
&gt;         }
&gt; 
&gt;         // Create Or Update Certificate
&gt;         [NUnit.Framework.Test]
&gt;         [NUnit.Framework.Ignore(&quot;Only verifying that the sample builds&quot;)]
&gt;         public async Task CreateOrUpdate_CreateOrUpdateCertificate()
&gt;         {
&gt;             // Generated from example definition: specification/web/resource-manager/Microsoft.Web/stable/2021-02-01/examples/CreateOrUpdateCertificate.json
&gt;             // this example is just showing the usage of &quot;Certificates_CreateOrUpdate&quot; operation, for the dependent resources,
&gt; they will have to be created separately.
&gt; 
&gt;             // get your azure access token, for more details of how Azure SDK get your access token, please refer to
&gt; https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line
&gt;             TokenCredential cred = new DefaultAzureCredential();
&gt;             // authenticate your client
&gt;             ArmClient client = new ArmClient(cred);
&gt; 
&gt;             // this example assumes you already have this ResourceGroupResource created on azure
&gt;             // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource
&gt;             string subscriptionId = &quot;0151c365-f598-44d6-b4fd-e2b6e97cb2a7&quot;;
&gt;             string resourceGroupName = &quot;siliconrg&quot;;
&gt;             ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId,
&gt; resourceGroupName);
&gt;             ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
&gt; 
&gt;             // get the collection of this AppCertificateResource
&gt;             AppCertificateCollection collection = resourceGroupResource.GetAppCertificates();
&gt; 
&gt;             // invoke the operation
&gt;             string name = &quot;certsilicon&quot;;
&gt;             AppCertificateData data = new AppCertificateData(new AzureLocation(&quot;East US&quot;))
&gt;             {
&gt;                 Password = &quot;password&quot;,
&gt;                 HostNames = { &quot;ServerCert&quot; },
&gt;             };
&gt;             ArmOperation&lt;AppCertificateResource&gt; lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, name, data);
&gt;             AppCertificateResource result = lro.Value;
&gt; 
&gt;             // the variable result is a resource, you could call other operations on this instance as well
&gt;             // but just for demo, we get its data from this resource instance
&gt;             AppCertificateData resourceData = result.Data;
&gt;             // for demo we just print out the id
&gt;             Console.WriteLine($&quot;Succeeded on id: {resourceData.Id}&quot;);
&gt;         }
&gt;     } } 
&gt; ```

**Output:-**


![enter image description here](https://i.imgur.com/uTSKLjn.png)


</details>



# 答案2
**得分**: 0

如我在[我的其他帖子的答案][1]中所指示,要在应用服务自定义域绑定中使用自带的 PFX 证书,必须首先将其上传到密钥保管库。只有这样才能将其部署到应用服务证书池。

示例代码生成的是托管证书,而不是 PFX 证书,托管证书不支持通配符。如果不需要通配符,那就没问题。请谨慎操作,但可以继续。

但如果确实需要通配符,以下是如何将证书从保管库推送到用于绑定的 PFX 列表的方法:

```vb
Private Async Function DeployCertFromVault(Params As DeployParams) As Task
  Dim oCertificateCollection As AppCertificateCollection
  Dim oKeyVaultResponse As Response(Of KeyVaultResource)
  Dim oResourceGroup As Response(Of ResourceGroupResource)
  Dim oCertificate As AppCertificateData

  oResourceGroup = Await Params.Subscription.GetResourceGroups.GetAsync(My.Resources.PrimaryResourceGroup)
  oKeyVaultResponse = Await oResourceGroup.Value.GetKeyVaultAsync(My.Resources.VaultName)
  oCertificateCollection = oResourceGroup.Value.GetAppCertificates

  oCertificate = New AppCertificateData(Params.WebSiteResource.Data.Location) With {
    .KeyVaultSecretName = Params.CertName,
    .ServerFarmId = Params.WebSiteResource.Data.AppServicePlanId,
    .KeyVaultId = oKeyVaultResponse.Value.Id
  }

  Await oCertificateCollection.CreateOrUpdateAsync(WaitUntil.Completed, Params.CertName, oCertificate)
End Function

Public Structure DeployParams
  Public WebSiteResource As WebSiteResource
  Public Subscription As SubscriptionResource
  Public CertName As String
End Structure

查看我的答案获取其余内容。

英文:

As I indicated in the answer to my other post, a bring-your-own PFX cert to be used in an App Service Custom Domain binding has to be uploaded to a key vault first. Only then can it be deployed to the App Service certificate pool.

The sample code results in a managed cert, not a PFX cert, and managed certs don't support wildcards. If wildcard isn't a requirement, no problem. Proceed with caution, but proceed.

But if one is needed, here's how to push the cert from a vault to the PFX list for use in a binding:

Private Async Function DeployCertFromVault(Params As DeployParams) As Task
  Dim oCertificateCollection As AppCertificateCollection
  Dim oKeyVaultResponse As Response(Of KeyVaultResource)
  Dim oResourceGroup As Response(Of ResourceGroupResource)
  Dim oCertificate As AppCertificateData

  oResourceGroup = Await Params.Subscription.GetResourceGroups.GetAsync(My.Resources.PrimaryResourceGroup)
  oKeyVaultResponse = Await oResourceGroup.Value.GetKeyVaultAsync(My.Resources.VaultName)
  oCertificateCollection = oResourceGroup.Value.GetAppCertificates

  oCertificate = New AppCertificateData(Params.WebSiteResource.Data.Location) With {
    .KeyVaultSecretName = Params.CertName,
    .ServerFarmId = Params.WebSiteResource.Data.AppServicePlanId,
    .KeyVaultId = oKeyVaultResponse.Value.Id
  }

  Await oCertificateCollection.CreateOrUpdateAsync(WaitUntil.Completed, Params.CertName, oCertificate)
End Function

Public Structure DeployParams
  Public WebSiteResource As WebSiteResource
  Public Subscription As SubscriptionResource
  Public CertName As String
End Structure

Check my answer for the rest of it.

huangapple
  • 本文由 发表于 2023年5月21日 17:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定