使用C#的Azure REST Api身份验证 [英] Azure REST Api Authentication using C#
问题描述
我希望能够使用此调用获取有关我的Azure SQL数据库之一的信息:
I would like to be able to get information about one of my Azure SQL databases using this call: https://docs.microsoft.com/en-gb/rest/api/sql/manageddatabases/manageddatabases_get
When I use the Try It button and login to my account it works perfectly, however I can't get my C# function app to get an authentication token so it can work in C#. I've spent 3 days on this. I have tried the Keyvault way but haven't managed to set up the permissions correctly. Forgetting Keyvault, the nearest I've got I think is by using this code but I don't know what my app password is:
// 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;
}
When I use the Try It button and login to my account it works perfectly
When you click the Try it
, you use the user credential
with username and user_password to authenticate. And the code you provided is using App registered in Azure AD
to authenticate, and it would work well with the following steps you have followed.
1.As silent said, you need to create a Service Principle
in Azure Active Directory. You could refer to this article.
2.The Sign in value about TenantId
, clientId
and clientSecret
you could refer to this link.
3.Finally, you would access to Azure SQL Database, you need to add permission to you Azure AD App. Click the App you registered in Azure AD before and click Settings
, and add Require Permission
. After adding API access
, Grant Permission
.
这篇关于使用C#的Azure REST Api身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!