在 c# 中重新创建 Az.Connect-AzAccount



PowerShell在Az.Accounts库中有一个很棒的功能 - "Connect-AzAccount" - 允许我针对我的Azure实例进行身份验证并轻松发布APIM的。 我需要将代码移植到 c# 上,但找不到简单的等效项。

有没有人找到一种直接的方法? Azure 世界/库似乎经常更新,以及许多安全方面。 很难找到最近的相关示例。

我的最终目标是针对 Azure 进行身份验证,然后将 API 发布到 API 网关。

PowerShell代码:

$user = "account@domain.com"
$password = ConvertTo-SecureString -String "password goes here" -AsPlainText -Force
$azAccount = @{
subscription = "subscription-guid-goes-here"
credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $user,$password
}
Connect-AzAccount @azAccount

目前,适用于 .NET 的 Azure 管理库只能用于管理部分 Azure 资源。但是,不包括 Azure API 管理。

因此,我建议你使用 Azure REST API 来管理你的资源。

由于Azure REST APi受Azure AD保护。因此,第一步是获取用于身份验证的访问令牌。

下面是使用Microsoft.IdentityModel.Clients.ActiveDirectory包的示例

static string GetToken()
{
string tenantId = "your tenant id or name, for example: hanxia.onmicrosoft.com";
string clientId = "1950a258-227b-4e31-a9cf-717495945fc2"; // it is a public client for every tenant. 
string resource = "https://management.core.windows.net/";
string username = "user name, jack@hanxia.onmicrosoft.com";
string password = "password, D******";
var upc = new UserPasswordCredential(username, password);
var context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
AuthenticationResult result = context.AcquireTokenAsync(resource, clientId, upc).Result;
return result.AccessToken;
}

之后,可以调用 Azure REST API 以及添加授权标头。下面是一个 POST 请求示例:

public static string postRequest(string url, string access_token, string data)
{
byte[] buffer = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "post";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + access_token);
//request.Headers.Add("other header", "it's value");
if (data != null)
buffer = Encoding.UTF8.GetBytes(data);
else
buffer = Encoding.UTF8.GetBytes("");
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return response.StatusCode + " " + reader.ReadToEnd();
}
}

现有的答案有点奇怪,它链接了一些旧的折旧库。官方库支持"管理"API 管理。这将是使用 C# 管理 Azure 资源的首选方法,无需重新创建任何内容。

最新更新