【问题标题】:Authenticate at subscription level using Azure SDK使用 Azure SDK 在订阅级别进行身份验证
【发布时间】:2021-11-07 04:56:52
【问题描述】:

我正在尝试从订阅中获取应用服务列表,以便我可以过滤暂存站点并使用 Azure SDK 将其删除。我遇到了未正确验证或无法查看订阅中的任何资源的问题。

我在订阅中拥有“所有者”角色,因此我应该可以完全访问订阅及其资源,但是在尝试遵循 Microsoft 的身份验证文档时 (https://docs.microsoft.com/en-us/dotnet/azure/sdk/authentication) 我似乎找不到在订阅级别进行身份验证的方法

这是我的代码:

                var azurecreds = SdkContext.AzureCredentialsFactory
                   .FromServicePrincipal(
                       "???",  //client ID
                       "???",  //client secret
                       "have this",  //tenant ID
                       AzureEnvironment.AzureGlobalCloud);

                var azure = Azure
                    .Configure()
                    .Authenticate(azurecreds)
                    .WithSubscription("have this");    //subscription ID

                //attempts with hard-coded values but not working
                var appServicePlans = azure.AppServices.AppServicePlans.List();
                var appServicePlans2 = azure.WebApps.List();
                var appServicePlans2 = azure.AppServices.AppServicePlans.ListByResourceGroup("Staging");

【问题讨论】:

    标签: c# azure sdk subscription


    【解决方案1】:

    当您关注本文档时:Authenticate with token credentials

    因此,根据上述文档,您必须使用此命令创建服务主体:

     az ad sp create-for-rbac --sdk-auth
    

    创建此服务主体后,您将获得以下详细信息:

    从上图中你必须复制ClientIDClient SecretTenantIDSubscriptionId。在你记下这些提到的细节后,你可以把它们放在代码中。

    var azurecreds = SdkContext.AzureCredentialsFactory  
    .FromServicePrincipal(  
    "ClientID copied from the above step", //client ID  
    "Client Secret Copied from the above step", //client secret  
    "have this", //tenant ID  
    AzureEnvironment.AzureGlobalCloud);
    
      
    
    var azure = Azure  
    .Configure()  
    .Authenticate(azurecreds)  
    .WithSubscription("have this"); //subscription ID
    
      
    
    //attempts with hard-coded values but not working  
    var appServicePlans = azure.AppServices.AppServicePlans.List();  
    var appServicePlans2 = azure.WebApps.List();  
    var appServicePlans2 = azure.AppServices.AppServicePlans.ListByResourceGroup("Staging");
    

    【讨论】:

    • 太棒了,因为它返回了我在订阅中识别的对象!现在的问题是它正在处理错误的订阅。在正确的订阅上运行代码时,表示我未经授权。那么我是否需要在另一个订阅上创建一个单独的服务原则,如果需要,我如何在创建它时指定另一个订阅?
    • 您可以使用:az account set -s“您要为创建服务主体设置的订阅”
    • 这解决了订阅问题,因为我的代码现在可以列出和过滤我想要获取的登台站点。非常感谢您的帮助!
    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多