如何使用 C# REST API 使用 Bearer Token 进行身份验证来生成 Bearer Token?

How to generate Bearer Token using C# REST API Authenticate with Bearer Token?

我正在尝试创建 webjob 来执行令牌端点并生成不记名令牌并执行图形端点以查询图形?如何使用 C# REST Api 实现相同的目标?什么是令牌端点?以下是在 Postman 工具中生成的令牌的屏幕截图。

What is token end point?

https://login.windows.net/<tenant-id>/oauth2/token

How can I achive the same using C# REST Api?

如果你想在 Azure AD OAuth 中使用 Resource Owner Password Credentials Grant,你可能会从这个 blog 得到答案。以下是博客的片段。

注:

  1. 此外,请注意资源所有者密码授予不提供同意并且也不支持 MFA
  2. 请使用 native Azure AD application.
  3. 进行测试
  4. 将用户添加为应用程序所有者

The following are the parameters needed in Azure AD OAuth for resource owner

password grant.

Name

Description

grant_type - The OAuth 2 grant type: password

resource - The app to consume the token, such as Microsoft Graph, Azure AD Graph or your own Restful service

client_id - The Client Id of a registered application in Azure AD

username -The user account in Azure AD

password -The password of the user account

scope - optional, such as openid to get 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"];

测试结果: