C# 在c中重新创建Az.Connect-AzAccount#
PowerShell在Az.Accounts库中有一个很好的功能——“连接AzAccount”——它允许我对Azure实例进行身份验证,并轻松发布APIM。我需要将代码移植到c#,但找不到简单的等效代码 有没有人找到了一个简单的方法?Azure world/库似乎在频繁更新,还有许多安全方面。很难找到最近的相关例子 我的最终目标是针对Azure进行身份验证,然后将API发布到API网关 PowerShell代码:C# 在c中重新创建Az.Connect-AzAccount#,c#,azure,powershell,azure-api-management,azure-authentication,C#,Azure,Powershell,Azure Api Management,Azure Authentication,PowerShell在Az.Accounts库中有一个很好的功能——“连接AzAccount”——它允许我对Azure实例进行身份验证,并轻松发布APIM。我需要将代码移植到c#,但找不到简单的等效代码 有没有人找到了一个简单的方法?Azure world/库似乎在频繁更新,还有许多安全方面。很难找到最近的相关例子 我的最终目标是针对Azure进行身份验证,然后将API发布到API网关 PowerShell代码: $user=”account@domain.com" $password=Conv
$user=”account@domain.com"
$password=ConvertTo SecureString-String“密码在此处”-AsPlainText-Force
$azAccount=@{
subscription=“订阅guid位于此处”
credential=新对象-TypeName“System.Management.Automation.PSCredential”-ArgumentList$user,$password
}
连接AzAccount@AzAccount
当前,只能用于管理部分Azure资源。但是,不包括Azure API管理
所以,我建议你用它来管理你的资源
由于Azure REST APi受Azure AD保护。因此,第一步是获取用于身份验证的accesstoken
下面是一个使用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并添加授权标头。以下是请求后的示例:
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();
}
}
现有的答案有点奇怪,它与一些旧的折旧图书馆有关。支持。这将是使用C#管理Azure资源的首选方法,并且您不必重新创建任何内容。Azure REST API有一个新的应用程序,但我从未使用过它,因此无法说明它是否是一个可行的选项。您可以将代码保存到脚本中,并通过将其传递到
PowerShell.exe
从C#间接执行它。或者,您可以使用更直接地呼叫PowerShell。您可以建议他使用预发布软件包。但我不知道。对,这就是为什么不提它的原因。有道理。最好重新创建SDK。英雄联盟