Getting "The remote server returned an error: (400) Bad Request."Error while request AccessToken using Tenant

Vinay 31 Reputation points
2022-06-24T10:33:06.227+00:00

Hello Team,

Actually I am try to get AccessToken using Using the TenantId after Admin consent successfully completed admin by using the following endpoint "https://login.microsoftonline.com/common/adminconsent", then I am requesting the AccessToken Endpoint Using Tenant ID "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token" by using HttpWebRequest by passing all the required fields

tenant : 6292ef34-37a8-4687-b8b3-7dd8d54a8a42

public static string AdminConsentAccessToken(string tenant, string state = "", string admin_concent = "")
{
string postData="{\"client_id\":\"65577dd2-cc76-46af-a1ac-71582eac6af2\",\"scope\":\"https://graph.microsoft.com/.default\",\"client_secret\":\"HCZ8Q~MiE_lI5tXFwnqhMU.cQ-jcA.ZvLX5Pyc80\",\"grant_type\":\"client_credentials\"}"
string result = string.Empty;
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create($"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token");
httpRequest.Method = "POST"; ;
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/x-www-form-urlencoded";

            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))  

{
streamWriter.Write(postData);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
//exception
}

        return result;  
    }  

With this code I am getting following error : "The remote server returned an error: (400) Bad Request." and status : Protocol Error, can you please check code suggest what went wrong.

and i have tried this from post man also the i am getting 400 - Bad Request (The request cannot be fulfilled due to bad syntax.)

POST : https://login.microsoftonline.com/6292ef34-37a8-4687-b8b3-7dd8d54a8a42/oauth2/v2.0/token
Header : Content-Type : application/x-www-form-urlencoded
Body :
{
"grant_type": "client_credentials",
"client_id":"65577dd2-cc76-46af-a1ac-71582eac6af2",
"scope":"https://graph.microsoft.com/.default",
"client_secret": "HCZ8Q~MiE_lI5tXFwnqhMU.cQ-jcA.ZvLX5Pyc80"
}

Response :
{
"error": "invalid_request",
"error_description": "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 68beea44-7863-4e08-97c9-526ada9d0300\r\nCorrelation ID: 064a85fe-6d37-43bd-ae59-3dca04232188\r\nTimestamp: 2022-06-24 09:08:56Z",
"error_codes": [
900144
],
"timestamp": "2022-06-24 09:08:56Z",
"trace_id": "68beea44-7863-4e08-97c9-526ada9d0300",
"correlation_id": "064a85fe-6d37-43bd-ae59-3dca04232188",
"error_uri": "https://login.microsoftonline.com/error?code=900144"
}

can you please suggest on both

Microsoft Security | Microsoft Graph
{count} votes

Accepted answer
  1. CarlZhao-MSFT 46,371 Reputation points
    2022-06-27T08:43:45.953+00:00

    Hi @Vinay

    If you are using the graph api then I highly recommend using the graph SDK to get the token.

    using Azure.Identity;  
      
    var scopes = new[] { "https://graph.microsoft.com/.default" };  
      
    // Multi-tenant apps can use "common",  
    // single-tenant apps must use the tenant ID from the Azure portal  
    var tenantId = "{tenant id}";  
      
    // Values from app registration  
    var clientId = "{client id}";  
    var clientSecret = "{client secret}";  
      
    // using Azure.Identity;  
    var options = new TokenCredentialOptions  
    {  
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud  
    };  
      
    // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential  
    var clientSecretCredential = new ClientSecretCredential(  
        tenantId, clientId, clientSecret, options);  
          
    var accessToken = await clientSecretCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { });  
      
    Console.WriteLine(accessToken.Token);  
    

    215341-image.png

    Also, I've tried testing the client credential flow in postman and it works fine for me. Please check:

    215306-2022-06-27-164042.png


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.