我已在 Azure 中注册了一个应用程序。我可以通过密码授予从 oauth2/v2.0/token 获取 access_token
。我还可以使用refresh_token grant从oauth2/v2.0/token获取refresh_token
但是,如何使用 access_token
请求 Microsoft Azure 中的资源?
最佳答案
简而言之,我们如何在 azure 中使用生成的 access_token?
When you would request anything on azure you have to pass your access token as your request header
request.Headers.Authorization
which isBearer
token.
在这里,我为您提供了一个如何使用访问 token 访问 azure 资源的示例。
//New Block For Accessing Data from Microsoft Graph Rest API
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/users"));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
I am accessing
Azure Active Directory User List
usingaccess token
. I got this responseSee the screenshot below:
Azure 资源 API 访问示例:
根据 Gaurav Mantri's建议 我还为您提供了另一个示例,说明如何获取 azure 资源组信息。请参阅下面的代码片段
//How You Would Request Microsft Resource Management API For Resources List
var azureSubcriptionId = "Your_Azure_Subcription_Id";
var resourceGroupName = "Your_Resource_Group_Name";
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/resources?api-version=2019-10-01", azureSubcriptionId, resourceGroupName));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objAzureResourceGroupList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
还在 PostMan 上进行了测试。
更多详情可以引用Official Docs
希望这对您有帮助。
关于c# - 如何使用访问 token 请求 Microsoft Azure 资源?简而言之,我们如何在azure中使用生成的access_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60428067/