我正在运行ASP.NET Core应用程序(.Net Core 3.0),并引用了nuGet程序包Microsoft.Azure.Management.WebSites
。似乎有六种方法可以连接到Azure,我希望这对我的环境是正确的。
我正在尝试实例化WebSiteManagementClient
,以便可以修改某些AppService
设置(向上/向下扩展服务计划)。为此,我需要一个ServiceClientCredentials
的实例。我似乎找不到一种将适当的凭据收集在一起的方法。
我关注了几篇不同的文章,他们都主张采用不同的方法。
通过Azure管理SDK进行身份验证的最简单方法是什么?
理想情况下,避免使用Azure Active Directory。我已经尝试过多次尝试使用适当的权限来设置应用注册,但似乎无法将它们整合在一起。
连接并进行更改的应用将是在Azure本身中运行的ASP.NET网站,如果有帮助的话。
提前感谢!
到目前为止的代码:
using Microsoft.Azure.Management.WebSites;
var credentials = await GetCredentials(); // <-- ???
WebSiteManagementClient client = new WebSiteManagementClient(credentials);
client.SubscriptionId = "xxx-xxx-xxxx-xxxx";
尝试一下:
static void Main(string[] args)
{
string tenantId = "<your tenant ID>";
string clientId = "<your azure ad app ID>";
string clientSecret = "<azure ad app secret>";
string subscriptionId = "<your subscription ID>";
WebSiteManagementClient client = new WebSiteManagementClient(GetCredsFromServicePrincipal(tenantId, clientId, clientSecret));
client.SubscriptionId = subscriptionId;
foreach (var ap in client.app.List()) {
Console.WriteLine(ap.Id);
}
}
private static TokenCredentials GetCredsFromServicePrincipal(String tenantId,String clientId, String clientSecret)
{
var authority = @"https://login.microsoftonline.com/" + tenantId;
var authContext = new AuthenticationContext(authority);
var credential = new ClientCredential(clientId, clientSecret);
var authResult = authContext.AcquireTokenAsync("https://management.azure.com", credential).GetAwaiter().GetResult();
return new TokenCredentials(authResult.AccessToken);
}
结果(列出所有网站ID):由于此示例使用ServicePrincipal访问您的Azure网站资源,因此您应在订阅“访问控制(IAM)”秃头中为其授予关联的权限,例如为其分配“网站贡献者”和“网络计划贡献者”,以便它具有权限管理您的网站资源。希望对您有所帮助。