如果要使用服务主体调用 Azure 资源图 Rest API,则必须将Azure RABC 角色分配给 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

- 配置代码。请注意,如果要在不同的订阅中调用资源,则需要通过在 step1 中更改范围值来创建不同的服务主体
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.配置权限

创建客户端密码

配置代码。请参考样本