I've created a multi tenant Web API that works just fine. Now I want to build a native client for testing. The Web API app is defined in one tenant. The test app is defined in another tenant that has given admin consent to the Web API.
I want to use the native app to authenticate with username and password in my (non-interactive) integration tests. I cannot use certificate/app-only authentication because I need a real user context.
Getting a token
var userCredential = new UserCredential("admin@clienttenant.onmicrosoft.com", "password");
var context = new AuthenticationContext("https://login.windows.net/common");
return context.AcquireToken("https://webapitenant.onmicrosoft.com/webApiResourceUri", testClientId, userCredential).AccessToken;
The problem with this code is that it doesn't work until I've given admin consent to the native app, even if the user is in the same tenant as the app registration.
Exception thrown:
'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException' in Microsoft.IdentityModel.Clients.ActiveDirectory.dll
Additional information:
AADSTS65001: The user or administrator has not consented to use the application with ID 'nativeclientid'. Send an interactive authorization request for this user and resource.
Since tests aren't interactive I have to create a console application that uses the above code but with PromptBehaviour.Always
. This will prompt me for username and password and show a consent form. After I give consent the tests that is using the same native app registration starts working.
Is there a way to accept the consent form without a interactive GUI?