简体   繁体   中英

Not getting access_token by calling https://login.microsoftonline.com/{tenant}/oauth2/token

I want to get user email from user id (object identifier) from web api, but getting blank response while calling api for token. I am running this code from my Web API. Please help. Below is the code.

Given full permission to APIs

在此处输入图片说明

Getting Blank response in below line.

var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);

Below is code

var tenant = "tenant ID";
var clientID = "app ID";

// I've tried graph.microsoft.com and graph.microsoft.com/.default
var resource = "https://graph.microsoft.com";
var secret = "client secret";

string token;


using (var webClient = new WebClient())
                {
                    var requestParameters = new NameValueCollection();
                    requestParameters.Add("scope", resource);
                    requestParameters.Add("client_id", clientID);
                    requestParameters.Add("grant_type", "client_credentials");
                    requestParameters.Add("client_secret", secret);

                    var url = "https://login.microsoftonline.com/{tenant}/oauth2/token";
                   webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    var responseBytes = await webClient.UploadValuesTaskAsync(url, "POST", requestParameters);
                    var responseBody = Encoding.UTF8.GetString(responseBytes);

                    var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(responseBody);
                    token = jsonObject.Value<string>("access_token");
                }
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                var response = await client.GetAsync(new Uri("https://graph.microsoft.com/v1.0/user/" + ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")));

Your error is here:

requestParameters.Add("scope", resource);

It needs to be resource rather than scope :

requestParameters.Add("resource", resource);

Can you help me understand what documentation or tutorial you followed to make this mistake? I have seen it happen before and I am trying to understand the patterns here.

The documentation and authentication flow you should be following is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM