Search code examples
c#access-tokenazure-active-directory

Trying to get access token by AcquireTokenAsync but getting failed with exception body parameters must contain 'client_secret or client_assertion'


I am trying get access token without auth code, so using below method to get it. but i am facing issue as "the request body must contain the following parameter 'client_secret or client_assertion'"

Can you suggest necessary pointers on this. Running this in console application.

try
{
    // Use the 'Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory' Nuget package for auth.
    AuthenticationContext authContext = new AuthenticationContext(authority);
    AuthenticationResult authResult = authContext.AcquireTokenAsync(resourceId, clientId, new UserCredential(crmAdminUserName, crmAdminPassword)).Result;
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

Solution

  • Assuming the app is registered in the portal, and you know the client id, client secret key/app key, authority and audience

    Then this code snippet will get you the access token

    AuthenticationContext authContext = new AuthenticationContext(authority); ClientCredential clientCredential = new ClientCredential(clientId, clientkey); AuthenticationResult authenticationResult = await authContext.AcquireTokenAsync(ResourceUrl, clientCredential);

    Resource Id/Resource Url e.g. https://manage.windowsazure.com/{placeholder-for-your-azure-ad-tenant-name}.onmicrosoft.com

    AcquireTokenAsync documentation is available from here

    AuthenticationContext class documentation is available from here