Authentication from an ASPX Page

banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

In order to use the Web services from an APSX page, you must use the Microsoft.Crm.Sdk.CrmImpersonator class.

When used inside a using statement, the CrmImpersonator class allows a block of code to execute under the process credentials instead of the running thread's identity. At the end of the using statement, execution will return back to running under thread id. For more information see the MSDN documentation for ImpersonateSelf, located at http://msdn2.microsoft.com/en-us/library/aa378729.aspx.

Note    When you are using this class, you must set the ownerid property for the entity when you use the Create method or Create message. This is shown in the sample below.

For more information about impersonation, see the MSDN documentation, located at http://msdn2.microsoft.com/en-us/library/aa376391.aspx.


The following example shows how to use the CrmImpersonator class to authenticate in an ASPX page. This code sample works with Microsoft Dynamics CRM on-premise and IFD deployments and also running the ASPX page from within the online or offline Outlook client.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Win32;

namespace WebApplication1
    public partial class _Default : System.Web.UI.Page
        public string orgname;
        public string crmurl;
        public string metaurl;
        public bool offline;

        protected void Page_Load(object sender, EventArgs e)
            #region CRM URLs and Organization Name

            //Determine Offline State from Host Name
            if (Request.Url.Host.ToString() == "")
                offline = true;

                //Retrieve the Port and OrgName from the Registry
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
                orgname = regkey.GetValue("ClientAuthOrganizationName").ToString();
                string portnumber = regkey.GetValue("CassiniPort").ToString();

                //Construct the URLs
                string baseurl = "http://localhost:" + portnumber + "/mscrmservices/2007/";
                crmurl = baseurl + "crmservice.asmx";
                metaurl = baseurl + "metadataservice.asmx";
                offline = false;

                //Retrieve the URLs from the Registry
                RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
                string ServerUrl = regkey.GetValue("ServerUrl").ToString();
                crmurl = ServerUrl + "/2007/crmservice.asmx";
                metaurl = ServerUrl + "/2007/metadataservice.asmx";

                //Retrieve the Query String from the current URL
                if (Request.QueryString["orgname"] == null)
                    orgname = string.Empty;
                    //Query String
                    string orgquerystring = Request.QueryString["orgname"].ToString();
                    if (string.IsNullOrEmpty(orgquerystring))
                        orgname = string.Empty;
                        orgname = orgquerystring;

                if (string.IsNullOrEmpty(orgname))
                    //Windows Auth URL
                    if (Request.Url.Segments[2].TrimEnd('/').ToLower() == "isv")
                        orgname = Request.Url.Segments[1].TrimEnd('/').ToLower();

                    //IFD URL
                    if (string.IsNullOrEmpty(orgname))
                        string url = Request.Url.ToString().ToLower();
                        int start = url.IndexOf("://") + 3;
                        orgname = url.Substring(start, url.IndexOf(".") - start);


            using (new CrmImpersonator())
                CrmAuthenticationToken token;
                if (offline == true)
                    token = new CrmAuthenticationToken();
                    // Notice that the Context parameter value is Page.Context.
                    token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
                token.OrganizationName = orgname;
                token.AuthenticationType = 0;

                //Create the Service
                CrmService service = new CrmService();
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                service.CrmAuthenticationTokenValue = token;
                service.Url = crmurl;

            // This code shows how to create the metadata service.
            // It is not used in this sample.
            // MetadataService meta = new MetadataService();
            // meta.CrmAuthenticationTokenValue = token;
            // meta.Credentials = CredentialCache.DefaultCredentials;
            // meta.Url = "http://localhost/mscrmservices/2007/MetadataService.asmx";

                account account = new account();
                account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
                if (offline == false)
                    // Explicitly set the owner ID for the record if not offline.
                    account.ownerid = new Owner("systemuser", token.CallerId);



See Also


Other Resources

© 2010 Microsoft Corporation. All rights reserved.