Search code examples
azureazure-keyvaultdynamics-business-central

Error in getting access token for azure key vault in business central?


I am trying to POST an HTTP request with different parameters in the body, but i am getting the message "oauth2 error AADSTS90014: The request body must contain the following parameter: 'grant_type' ". Through Postman i am able to get the access token, with the same parameters. I don't know what i am doing wrong here. I have attached the screenshots as well.

If anyone can help me out.

JSONAddPair(vJsonObject, 'grant_type', 'client_credentials');
JSONAddPair(vJsonObject, 'client_id', 'client-id-here');
JSONAddPair(vJsonObject, 'client_secret', 'secret-here');
JSONAddPair(vJsonObject, 'scope', 'https://vault.azure.net/.default');
vJsonObject.WriteTo(Body);

URL := 'https://login.microsoftonline.com/' + DirectoryId + '/oauth2/v2.0/token';

vRequestContent.WriteFrom(Body);
vRequestContent.GetHeaders(vContentHeaders);
vContentHeaders.Clear();
vContentHeaders.Add('Content-Type', 'application/json');

vHttpRequestMessage.Method := 'POST';
vHttpRequestMessage.SetRequestUri(URL);
vHttpRequestMessage.Content := vRequestContent;

vHttpClient.Send(vHttpRequestMessage, vHttpResponseMessage);

vHttpResponseMessage.Content().ReadAs(ResponseText);
Message(ResponseText);

Post request through postman

error message


Solution

  • As @juunas said , you should post form data , instead of JSON . Try this :

    URL := 'https://login.microsoftonline.com/' + DirectoryId + '/oauth2/v2.0/token';
    
    vRequestContent.WriteFrom('grant_type=client_credentials&client_id=<client id here>&client_secret=<secret here>&scope=https://vault.azure.net/.default');
    vRequestContent.GetHeaders(vContentHeaders);
    vContentHeaders.Clear();
    vContentHeaders.Add('Content-Type', 'application/x-www-form-urlencoded');
    
    vHttpRequestMessage.Method := 'POST';
    vHttpRequestMessage.SetRequestUri(URL);
    vHttpRequestMessage.Content := vRequestContent;
    
    vHttpClient.Send(vHttpRequestMessage, vHttpResponseMessage);
    
    vHttpResponseMessage.Content().ReadAs(ResponseText);
    Message(ResponseText);
    

    If you get some errors such as in-correct secret, pls url encode your whole http request content.

    update : This issue has been solved when changed request body to plain text