problem when trying to redeem the token for user information in the microsoft graph api

Viewed 92

once the user logs in with his microsoft account in the web application, a redirection is made to a method which aims to extract the user code and exchange it for the token, finally when I try to use the token with the api , when making the http request through the get method, it fails, here I show the code, it was make on C#:

var EmailRequest = "https://graph.microsoft.com/v1.0/me/?$select=displayName";
var Request = WebRequest.Create(EmailRequest);
Request.Headers.Add("Authorization", "Bearer " + accessToken );
var Response = (HttpWebResponse)Request.GetResponse(); 

1 Answers

Seems you are trying to get User displayName once the user login into web application.

Its depends how are you getting token, If you are getting token using Client_Credentialprotocol you wouldn't get displayName using query parameters like this. You have to use ROPC if you want to get like this.

You could try following way:

Token And API Request

            string tokenUrl = $"https://login.microsoftonline.com/YourTenent/oauth2/token";
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = "b603c7be-a866_client_id_6921e61f925",
                ["client_secret"] = "Vxf1SluKb_client_secret_eZ8wL/Yp8ns4sc=",
                ["resource"] = "https://graph.microsoft.com",
                ["username"] = "Login_User_Name.onmicrosoft.com",
                ["password"] = "User_Password"

            });

            dynamic json;
            dynamic results;

            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

            //New Block For Accessing Data from Microsoft Graph API
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/?$select=displayName");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
            HttpResponseMessage response = await client.SendAsync(request);

            dynamic selectUserDisplayName = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

Class Used

public class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
        public string refresh_token { get; set; }

    }

enter image description here

You could refer to this Official Document Hope this would help you.

Related