UPDATE: Please review the comments for this post. There is a better, easier way to do this using OAuth that works with both the SOAP and REST/OData service.
Sometimes you need to run ASP.NET code outside of Dynamics CRM to achieve your goals. This usually manifests itself either as a page embedded in CRMs main content area which is accessible via a link in the sitemap similar to the following:
Another place this is often used is embedding external content through an IFrame in a CRM form. The general approach is covered in the SDK:
Of course, your code will usually need to call back into Dynamics CRM through the organization (web) service to do things like CRUD on CRM data, etc. In this scenario, you want CRM to execute code under the context of the logged in user. The CRM SDK covers how to do this here:
See my CRM Online & Windows Azure Series post for a walkthrough of the Single Sign On (SSO) configuration. The goal of this post is to bring all of these concepts together in as simple of a “hello world” style code sample as possible. The sample code is actually the code for the embedded page in the screenshot above (called ActOnBehalfOf.aspx). The solution is made up of an ASP.NET web form, some code behind the web form, and a helper class I built. In order to get this code to compile, you are going to have to add the necessary .NET assembly references and fix some of the namespaces. I’ll leave that exercise to you.
If you’ve reviewed the resources in this post, then ActOnBehalfOf.aspx and ActOnBehalfOf.aspx.cs should be pretty self explanatory. It’s a page with a GridView. The code behind queries CRM for data using the organization service. Note that Account from line 19 comes from a class file where I used crmsvcutil.exe to generate the class. I always use Erik Pool’s approach to only generate classes I need in my code. I digress. The code sets the CallerId property of the CrmConnection object instance before executing the code. By doing this, CRM will execute all calls made to through the OrganizationServiceContext instance as the CRM user based on the CallerId value passed in. CallerId is the GUID of the CRM user who needs to be impersonated. The ActOnBehalfOfHelper does the real work to get the proper GUID based on the claims available to the ASP.NET page. Specifically, it uses the UPN claim value to find the CRM user. Once the CRM user is found, the code returns the Id of the CRM user as a GUID.
Note the comments in the code. I am doing some caching of the user GUID in a cookie. Right now, the cookie and cookie value is in plain text. As I state, this is done for simplicity of the sample. Make sure you read the comments and make the proper adjustments to protect access to the CallerID GUID from malicious code/callers.