How to generate Bearer Token using C# REST API Aut

2020-03-31 10:14发布

问题:

I am trying to create webjob to execute Token end point and generate the bearer token and execute Graph End Point to Query graph? How can I achive the same using C# REST Api? What is token end point? Following is the screenshot for token genrated in Postman tool.

回答1:

What is token end point?

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

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

If you want to use Resource Owner Password Credentials Grant in Azure AD OAuth, you may get the answer from this blog. The following is the snippet from the blog.

Note:

  1. Furthermore, notice that resource owner password grant doesn't provide consent and doesn't support MFA either
  2. Please test with native Azure AD application.
  3. Add the user as the Application owner

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

Demo code:

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"];
    }
  }
}

Updated:

According to your comment, I also do a demo with RestClient.

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"];

Test result: