从 .NET 应用程序调用 Azure Resource Graph API

Call the Azure Resource Graph API from .NET Application

我正在尝试编写一个应用程序,允许用户从我的应用程序中的 Azure 订阅中查询网站列表。我不想将他们的凭据存储在我的应用程序中(他们也不希望我这样做),而是我会要求他们从他们的 Azure AD 实例中注册一个应用程序,然后让他们存储在我的应用程序中生成的 ClientID 和 TenantID应用程序。我会给他们一组关于如何从他们的 Azure 门户执行此操作的说明,该门户使用尽可能严格的权限,并且他们可以随时关闭。他们需要像我一样感到舒服。

我正在尝试按照本文的情节进行操作:

它让我非常接近,但是当我 运行 应用程序时,我从 Azure Resource Graph 得到了 "Forbidden" 响应,因此呼叫接通但被拒绝。我还尝试使用我自己的 Azure 门户添加各种 API 权限进行测试。文章说我需要使用以下方法创建服务主体:

az ad sp create-for-rbac -n "MyApp" --role contributor --sdk-auth

我还没有做。

所以我的问题是:

我感谢任何人可以提供的任何指导或文章推荐。

非常感谢....

如果要使用服务主体调用 Azure 资源图 Rest API,则必须将 Azure RABC Role 分配给 sp。所以你必须运行下面的命令

# it will create a service pricipal and assign a contributor rolen to the sp
az ad sp create-for-rbac -n "MyApp"  --scope "/subscriptions/<subscription id>" --sdk-auth


# if you have a service principal, please run the following script
az ad sp list --display-name "{name}" --query [].objectId --output tsv
az role assignment create --assignee <sp object id> --role "Contributor " --scope "/subscriptions/<subscription id>"

同时,运行样本的详细步骤如下 1. 运行 以下脚本。

az login
az ad sp create-for-rbac -n "MyApp"  --scope "/subscriptions/<subscription id>" --sdk-auth

  1. 配置代码。请注意,如果要在不同的订阅中调用资源,则需要通过更改步骤1中的范围值来创建不同的服务主体
public  async static Task Test() {


            CustomLoginCredentials creds = new CustomLoginCredentials();

            var resourceGraphClient = new ResourceGraphClient(creds);

            var queryReq = new QueryRequest {

                Subscriptions = new List<string> { "<the subscriptionId you copy>" },
                Query = "where type == 'microsoft.web/sites'"

            };
            var result = await resourceGraphClient.ResourcesAsync(queryReq);
            Console.WriteLine(result.Count);
        }

class CustomLoginCredentials : ServiceClientCredentials {
        private static string tenantId = "<the tenantId you copy >";
        private static string clientId = "<the clientId you copy>";
        private static string cert = "<the clientSecre tyou copy>";
        private string AuthenticationToken { get; set; }
        public override void InitializeServiceClient<T>(ServiceClient<T> client)
        {
            var authenticationContext =
                new AuthenticationContext("https://login.microsoftonline.com/"+tenantId);
            var credential = new ClientCredential(clientId: clientId, clientSecret: cert);

            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/",
                clientCredential: credential).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            AuthenticationToken = result.AccessToken;
        }
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (AuthenticationToken == null)
            {
                throw new InvalidOperationException("Token Provider Cannot Be Null");
            }



            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);



            await base.ProcessHttpRequestAsync(request, cancellationToken);

        }

详情请参考

https://odetocode.com/blogs/scott/archive/2018/02/01/setting-up-service-principals-to-use-the-azure-management-apis.aspx

https://docs.microsoft.com/en-us/cli/azure/ad/sp?view=azure-cli-latest#az-ad-sp-create


更新

根据您的需要,我认为您可以创建一个 Web 应用程序来调用 Azure Resource Graph API。如果这样做,您可以提供 Web 应用程序的 url,然后您的客户可以登录您的应用程序并自行调用 API。 1. 注册 Azure AD Web 应用程序

2.Configure 权限

  1. 创建客户端密码

  2. 配置代码。请参考sample