如何以编程方式获取 azure cli 访问令牌?

时间:2021-05-17 12:04:34

标签: .net azure

我必须查询 azure 才能在相当于下面 az cli 命令的资源组中获取 vmss:

az vmss list --resource-group <resource-group>  -o json

在内部调用rest-api:

GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets?api-version=2020-12-01

我需要在 c-sharp 中以编程方式获取上述信息。使用 rest API 客户端需要 jwt 令牌来调用上面的 API。根据文档,以下是获取 jwt 的 URL:

GET https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id={clientId} ...

我可以通过 az login 命令到达 URl 以上。但是,这是一个交互式命令,它要求用户输入登录 ID、密码,并有一个重定向 URL 到在 localhost 中运行的 api 接收令牌。

是否有任何 API 以 json 形式返回身份验证令牌?

3 个答案:

答案 0 :(得分:1)

您可以使用服务主体凭据而不是用户凭据。确保服务主体可以访问所需的资源以使用生成的令牌执行任何操作。

您可以通过 https://login.microsoftonline.com/{{TenantID}}/oauth2/token REST API 获取访问令牌。

您可以查看here了解更多详情。

答案 1 :(得分:1)

如果您不需要用户上下文,则应使用托管身份进行身份验证。托管身份是一个托管服务主体。

根据您运行工作负载的位置,您有多种获取令牌的选项:

答案 2 :(得分:1)

在您的情况下,您可以简单地使用 VisualStudioCredentialAzure.Identity 进行身份验证并获取令牌 NuGet here

VisualStudioCredential是使用登录VS的用户账号直接进行认证,参考下面的示例,accessToken是你要调用REST API的token。

示例:

using Azure.Core;
using Azure.Identity;
using System;
using System.Threading;

namespace ConsoleApp2
{
    class Program
    {
        public static void Main(string[] args)
        {
            TokenCredential tokenCredential = new VisualStudioCredential();
            TokenRequestContext requestContext = new TokenRequestContext(new string[] { "https://management.azure.com" });
            CancellationTokenSource cts = new CancellationTokenSource();
            var accessToken = tokenCredential.GetToken(requestContext, cts.Token).Token;

        }
            
    }
}

注意:在此示例中,您还可以将 VisualStudioCredential 更改为其他凭据,例如ClientSecretCredentialDefaultAzureCredentialManagedIdentityCredential 等,详情here,您可以根据自己的需求选择。


另外,其实你的情况不需要手动调用REST API,你可以直接使用.net SDK Azure.ResourceManager.Compute,使用VirtualMachineScaleSetsOperations.List(String, CancellationToken) Method列出资源组下的所有 VM 规模集,下面的 vmssList 就是您想要的。

示例:

using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager.Compute;
using System.Linq;


namespace ConsoleApp2
{
    class Program
    {
        public static void Main(string[] args)
        {
            var subscriptionid = "<your-subscription-id>";
            var rgname = "<group-name>";
            TokenCredential tokenCredential = new VisualStudioCredential();
            ComputeManagementClient client = new ComputeManagementClient(subscriptionid, tokenCredential);
            var vmssList = client.VirtualMachineScaleSets.List(rgname).ToList();
      
        }
    
    }
}

enter image description here