Search code examples
c#azureoauth-2.0

How to use OBO-flow with Flow app and Azure Function


I have a Power Automate flow in which I call https://login.microsoftonline.com/{tenantId}/oauth2/token with the following body:

grant_type=client_credentials
&client_id={clientId}
&client_secret={clientSecret}
&resource={app_registration}

The access token I receive from the call is being sent to an Azure Function app that needs to connect to Dynamics CRM. The Azure function tries to make a call to the Microsoft Identity Platform again with the same ClientId and ClientSecret and using the received bearer token as a new Userassertion(req.GetBearerToken())

The full relevant code in the Azure Function is as follows:

AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
ClientCredential credential = new ClientCredential("{clientId}", "{clientSecret}");
AuthenticationResult res = await authContext.AcquireTokenAsync("https://admin.services.crm.dynamics.com/user_impersonation", credential, new UserAssertion(req.GetBearerToken()));
string bearerTokenforCRM = res.AccessToken;

A silent sign-in request was sent but no user is signed in

I think I can't use the bearer token acquired from the /token call in the Flow app to acquire a new token on behalf of the user that started the flow app.

In the App Registration in Azure, I added the Azure function in the menu "Expose an Api" and added "Dyanmics CRM" in the menu API Permissions with permission name "user impersonation"


Solution

  • I believe you are a bit overcomplicating things - you can use the connection strings with ClientId/ClientSecret in order to connect to Dataverse using the following nuget package - https://www.nuget.org/packages/Microsoft.PowerPlatform.Dataverse.Client You can use the following article in order to build your connection string - https://learn.microsoft.com/en-us/power-apps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect Basically it should look like the following:

    AuthType=ClientSecret;
    url=https://contosotest.crm.dynamics.com;
    ClientId={AppId};
    ClientSecret={ClientSecret}
    

    In order to impersonate and perform actions on behalf of another user you can set the CallerId property of the service instance - https://learn.microsoft.com/en-us/dotnet/api/microsoft.xrm.tooling.connector.crmserviceclient.callerid?view=dataverse-sdk-latest#microsoft-xrm-tooling-connector-crmserviceclient-callerid