c# - 如何使用访问 token 请求 Microsoft Azure 资源?简而言之,我们如何在azure中使用生成的access_token?

标签 c# azure azure-active-directory

我已在 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 headerrequest.Headers.Authorization which is Bearer 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 using access token. I got this response

See the screenshot below:

enter image description here

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 上进行了测试。

enter image description here

更多详情可以引用Official Docs

希望这对您有帮助。

关于c# - 如何使用访问 token 请求 Microsoft Azure 资源?简而言之,我们如何在azure中使用生成的access_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60428067/

相关文章:

azure - 我无法启动 Azure 诊断监视器

php - 如何使用 PHP 的共享访问签名在 azure 中上传 blob?

azure - 获取 Azure 错误 : IDW10203: The 'scope' or 'scp' claim does not contain scopes 'access_as_machine' or was not found

c# - 将 JSON 反序列化为多个继承类

属性的 C# 自定义序列化

azure - 在 Azure Application Insights 中,EvenCounter 和预聚合指标之间有什么区别?

c# - 响应状态码不表示成功 : 404 (Not Found) with owin library

c# - 修改集合中对象的属性

c# - 如何在没有导航页面的情况下更改状态栏颜色

azure - Azure AD Multi-Tenancy SaaS 应用程序的租户特定主页 URL