我希望能够使用以下调用获取有关我的Azure SQL数据库之一的信息:https://docs.microsoft.com/en-gb/rest/api/sql/manageddatabases/manageddatabases_get
当我使用Try It按钮并登录到我的帐户时,它可以正常运行,但是我无法让我的C#函数应用程序获取身份验证令牌,因此它可以在C#中运行。我花了三天时间。我尝试了Keyvault的方法,但是没有正确设置权限。忘记Keyvault了,我想我最接近的是通过使用此代码,但我不知道我的应用密码是什么:
// I am using:
// tenant id is the Azure AD client id
// client id is the application id of my function app in Azure AD
public static string GetAccessToken(string tenantId, string clientId, string clientSecret)
{
var authContextUrl = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextUrl);
var credential = new ClientCredential(clientId, clientSecret );
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
var token = result.AccessToken;
return token;
}
答案 0 :(得分:0)
当我使用“试用”按钮并登录到我的帐户时,它运行正常
单击Try it
时,将user credential
与用户名和user_password一起使用进行身份验证。您提供的代码正在使用App registered in Azure AD
进行身份验证,并且可以很好地配合您执行的以下步骤。
1。正如沉默所说,您需要在Azure Active Directory中创建一个Service Principle
。您可以参考此article。
2。关于TenantId
,clientId
和clientSecret
的登录值,您可以参考此link。
3。最后,您将访问Azure SQL数据库,您需要向Azure AD App添加权限。单击之前在Azure AD中注册的应用,然后单击Settings
,然后添加Require Permission
。在adding API access
之后,Grant Permission
。
答案 1 :(得分:0)
我找到了一个对我有用的答案(经过三天的尝试,尝试了不同的东西并尝试在网络上阅读有关它的文章-我认为它没有很好的记录)。
此链接包含一些powershell步骤:
https://msftstack.wordpress.com/2016/01/03/how-to-call-the-azure-resource-manager-rest-api-from-c/
这些是我在PowerShell中尝试过的步骤
Login-AzureRmAccount
Get-AzureRmSubscription
Select-AzureRmSubscription –SubscriptionID “id”
$SecurePassword=ConvertTo-SecureString <my password> –asplaintext –force
$azureAdApplication = New-AzureRmADApplication -DisplayName “my ARM App” -HomePage
“https://<a home page>” -IdentifierUris “https://<a home page>” -Password $SecurePassword
New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azureAdApplication.ApplicationId
Get-AzureRmSubscription
$subscription = Get-AzureRmSubscription –SubscriptionId "id"
$creds=get-credential
(enter application id and password at this point)
Login-AzureRmAccount -Credential $creds -ServicePrincipal -Tenant $subscription.TenantId