How can I query Dynamics 365 CRM as the logged in user in an ASP.NET MVC site authenticated with AAD?

Viewed 541

I have an ASP.NET MVC website. Locally, and when deployed to Azure, it authenticates users in our organization with Azure Active Directory. Once authenticated, User.Identity is a System.Security.Claims.ClaimsIdentity.

I can query Dynamics CRM (hosted in the cloud, so Dynamics 365 CRM online) by embedding a username and password into the connection string and using Microsoft.Xrm.Tooling.Connector.CrmServiceClient namespace. The connection string looks like:

"Url=https://organization.crm.dynamics.com; Username=user@organizationURL.com; Password=passwordhere; authtype=Office365"

...but I want to avoid creating an application user account and I'd prefer to use the ambient security identity to connect to CRM as the authenticated user. How can I do this? Am I using the wrong SDK or package? I'm having a hard time finding a modern example or documentation that is intended for programmers rather than IT configuration.

When registering the website in Azure, I indicated that the user will need grant permission to interact with Dynamics CRM on their behalf, and I was prompted for this permission when I logged in, but as the programmer, I'm not sure how to actually use this permission.

2 Answers

I recommend you to use CRM REST web api along with a header CallerObjectId (for impersonation) which is guid of current logged-in user Azure AD object id. This will make sure the api call is made in user context. Of course you have to use AAD challenge/SSO in your MVC website and/or graph api capture the current AAD user guid.

Example payload:

POST [Organization URI]/api/data/v9.0/accounts HTTP/1.1  
CallerObjectId: e39c5d16-675b-48d1-8e67-667427e9c084  
Accept: application/json  
Content-Type: application/json; charset=utf-8  
OData-MaxVersion: 4.0  
OData-Version: 4.0  
  
{"name":"Sample Account created using impersonation"}

Read more

Still you have to use Application user for generating token and access the web api.

(My reputation is too low to comment, so I'll add this as an answer instead)

I agree with Arun's recommendation to use the CRM REST web api along with CallerObjectId. But I don't think it is necessary to use AAD challenge/SSO in your MVC website. If you $select the property azureactivedirectoryobjectid from /api/data/v9.1/systemusers you should find the needed AAD user guid there.

Related