我怎样才能获得可以传递给 azure rest 的不记名令牌 api

How I can I get the bearer token that i can pass to azure rest api

我想使用 azure-vm-rest-api 从 c# 创建虚拟机。我的问题是我没有 clientID 和 tenantID。我只有我的 Microsoft 用户名和密码。我正在尝试 POSTMAN 的 rest API 并且我成功地做到了。意味着我已经从 Deploy try it 部分获取了不记名令牌。我想从代码生成它。

使用此门户获取不记名令牌。

https://docs.microsoft.com/en-us/rest/api/resources/deployments/createorupdate(尝试部分) 一旦我登录,它将 return 我的不记名令牌。我在邮递员电话中使用的不记名令牌。

现在我想知道如何从 C# 生成不记名令牌,以便在从 C# 调用它时将其传递给 REST API。我没有任何客户和租户 ID。

  1. 您可以从 Azure 门户获取您的租户 ID。您可以通过以下方式找到它:Azure Active Directory -> Properties -> Directory ID。但是,在大多数情况下,您可以只使用您的租户名称,它是您帐户 ID 中“@”之后的部分。 (***.onmicrosoft.com 或您的自定义域)

  2. 创建一个 .NEt 框架应用程序并从 nuget 安装 Microsoft.IdentityModel.Clients.ActiveDirectory 包。

  3. 代码:

    class Program
    {
        static void Main(string[] args)
        {
            string tenantId = "your tenant id or tenant name";
            string clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
            string resource = "https://management.core.windows.net/";
            string username = "your work account, jack@hanxia.onmicrosoft.com";
            string password = "your password";

            var upc = new UserPasswordCredential(username, password);
            var context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
            AuthenticationResult result = context.AcquireTokenAsync(resource,clientId,upc).Result;
            Console.WriteLine(result.AccessToken);
            Console.ReadLine();
        }
    }

然后您可以使用访问令牌调用 Azure REST API。

更新:

您收到错误消息是因为您的管理员启用了 MFA。因此您将无法使用密码授予流程直接获取令牌。将有 4 种解决方法:

  1. 交互式获取令牌。

  2. 使用客户端凭据为您的应用程序获取令牌并管理资源。

  3. 为用户获取一次token,将获得一个refresh token。您可以使用它来获取新令牌。 Refreshing the access tokens

  4. 用乔伊的方式。您可以使用托管身份。

您可以使用 Microsoft.Azure.Services.AppAuthentication 库来做到这一点。

static void Main(string[] args)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
            Console.WriteLine(accessToken);
        }

关于认证的更多细节,你可以参考这个link. 是一个类似的例子,使用token调用其余的api,你也可以看看[=14] =]

public static string accessToken = string.Empty;     
 static void Main(string[] args)
            {
                try
                {
                    GetTokenWithoutSecretCode();
                    string url = "https://management.azure.com/subscriptions/SubscriptionID/resourcegroups/ResourceGroupName/providers/Microsoft.Resources/deployments/detdepoyment?api-version=2019-05-01";
                    string jsonContent = "{ \"properties\": {   \"templateLink\": {     \"uri\": \"https://storageName.blob.core.windows.net/templates/VMTemplate.json\",     \"contentVersion\": \"1.0.0.0\"   },   \"parametersLink\": {     \"uri\": \"https://storageName.blob.core.windows.net/templates/VMParam.json\",     \"contentVersion\": \"1.0.0.0\"   },   \"mode\": \"Incremental\" }}";
                    SpinupVM(url, jsonContent, accessToken);
                }
                catch (Exception ex)
                {
                    string message = ex.Message;
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }
            }

            private static void GetTokenWithoutSecretCode()
            {
                try
                {

                    AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                    accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
                }
                catch
                {
                    throw;
                }
            }

            // POST a JSON string
            private static void SpinupVM(string url, string jsonContent, string authToken)
            {
                JObject json = JObject.Parse(jsonContent);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "PUT";
                request.Headers.Add("Authorization", "Bearer " + authToken);
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                Byte[] byteArray = encoding.GetBytes(json.ToString());
                request.ContentLength = byteArray.Length;
                request.ContentType = "application/json";
                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }
                long length = 0;
                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        length = response.ContentLength;
                    }
                }
                catch
                {
                    throw;
                }
            }

要创建此 VM,您必须拥有相应的权限。您必须至少被添加为该资源组的贡献者。