【发布时间】:2018-01-15 12:23:35
【问题描述】:
我正在尝试创建 webjob 来执行 Token 端点并生成承载令牌并执行 Graph End Point 来查询图?如何使用 C# REST Api 实现相同的目标?什么是令牌端点?以下是 Postman 工具中生成的令牌的屏幕截图。
【问题讨论】:
标签: azure azure-cosmosdb azure-webjobs
我正在尝试创建 webjob 来执行 Token 端点并生成承载令牌并执行 Graph End Point 来查询图?如何使用 C# REST Api 实现相同的目标?什么是令牌端点?以下是 Postman 工具中生成的令牌的屏幕截图。
【问题讨论】:
标签: azure azure-cosmosdb azure-webjobs
什么是令牌端点?
https://login.windows.net/<tenant-id>/oauth2/token
如何使用 C# REST Api 实现相同的目标?
如果你想在 Azure AD OAuth 中使用 Resource Owner Password Credentials Grant,你可以从这个blog 得到答案。以下是博客中的sn-p。
注意:
以下是 Azure AD OAuth 中资源所有者所需的参数
密码授予。
名字
说明
grant_type - OAuth 2 授权类型:密码
resource - 使用令牌的应用,例如 Microsoft Graph、Azure AD Graph 或您自己的 Restful 服务
client_id - Azure AD 中已注册应用程序的客户端 ID
用户名 - Azure AD 中的用户帐户
password - 用户帐号的密码
scope - 可选,如openid获取Id Tok
演示代码:
using (HttpClient client = new HttpClient())
{
var tokenEndpoint = @"https://login.windows.net/<tenant-id>/oauth2/token";
var accept = "application/json";
client.DefaultRequestHeaders.Add("Accept", accept);
string postBody = @"resource=https%3A%2F%2Fgraph.microsoft.com%2F
&client_id=<client id>
&grant_type=password
&username=xxx@xxx.onmicrosoft.com
&password=<password>
&scope=openid";
using (var response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
{
if (response.IsSuccessStatusCode)
{
var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
token = (string)jsonresult["access_token"];
}
}
}
更新:
根据你的评论,我也用RestClient做了一个demo。
var tenantId = "xxxxxx";
var client = new RestClient("https://login.windows.net/");
var request = new RestRequest($"{tenantId}/oauth2/token", Method.POST);
//// easily add HTTP Headers
request.AddHeader("Accept", "application/json");
string postBody = @"resource=https://graph.microsoft.com/&client_id=xxxxx&grant_type=password&username=xxxxx&password=xxxxx&scope=openid";
request.AddParameter("application/x-www-form-urlencoded", postBody, ParameterType.RequestBody); //add request text body
IRestResponse response = client.Execute(request);
var content = response.Content;
var token = JObject.Parse(content)["access_token"];
【讨论】: