I registered new application as Web app / API (not native), added permission to Access Dynamics 365 as organization users.
I following this guide (https://code.msdn.microsoft.com/simple-web-api-quick-start-e0ba3d6b) which has the below code, the only difference is that I have updated my Microsoft.IdentityModel.Clients.ActiveDirectory
library which required small code change.
//Obtain the Azure Active Directory Authentication Library (ADAL)
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUrl + "api/data/")).Result;
AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
//Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, clientId, new Uri(redirectUrl),
new PlatformParameters(PromptBehavior.Always)).Result;
When I run this I getting a popup where I fill in my credentials and then it throws this error:
AdalException: {"error":"invalid_client","error_description":"AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.\r\nTrace ID: xxx\r\nCorrelation ID: xxx\r\nTimestamp: 2018-06-28 10:17:20Z","error_codes":[70002],"timestamp":"2018-06-28 10:17:20Z","trace_id":"xxx","correlation_id":"xxx"}: Unknown error
I tried to add the client_secret by applying the change below but it still doesn't work
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, clientId, new Uri(redirectUrl),
new PlatformParameters(PromptBehavior.Always), UserIdentifier.AnyUser,
$"client_secret={clientSecret}").Result;
But when I run this it does work, but this is not what I want, I want to login with specific user.
AuthenticationResult authResult = authContext.AcquireTokenAsync(
serviceUrl, new ClientCredential(clientId, clientSecret)).Result;
The Client Credential and Client Assertion authentication flows are meant for service to service communication, without user involvement. So your Web Api would access Dynamics not in the context of a user, but as itself.
Have a look at the official wiki to understand more: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/Client-credential-flows
Also, please be aware that we cannot help you if you make changes to Microsoft.IdentityModel.Clients.ActiveDirectory. You'd also miss out on updates, some of which are security critical. But feel free to propose changes if you think others would benefit!