Execute action with an Entity as input parameter using Web API in Dynamics CRM 2016

“Executing action using Web API” – well this is a topic which has become banal. It’s been talked about, people are using it every now and then in their projects. After all 2016 has just swayed away the consultants and customers alike. In-fact I wrote a blog on the same topic almost 6 months back in January when CRM 2016 was in it’s early days.


Although this blog post was much appreciated and I cannot thank the readers more for this, I have getting repeated questions about multiple scenarios related to this and one of them is – How do I execute a global action using Web API with an entity as input parameter. Mostly in the examples shared on the blog, the input parameters are boolean and string.

So I decided to pen it down here. So let’s take a very simple example here.

For this demo, I have created an action named ‘Test Action’. That is a global action with Entity as the input parameter. The Entity type is account.


Now coming to the code. Below is the sample code to do the same.

function callAction() {

    var organizationUrl = Xrm.Page.context.getClientUrl();

    var account = {};
    account.name = "Test Account Name";
    account.description = "This account was created for action test.";
    account.revenue = 2000000.00; // decimal
    account.donotphone = true; //boolean field
    //account.logicalname = "account";
    var data = { "EntityArg": account };

    var query = "new_TestAction";
    var req = new XMLHttpRequest();
    req.open("POST", organizationUrl + "/api/data/v8.0/" + query, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var data = JSON.parse(this.response);

            } else {
                var error = JSON.parse(this.response).error;



What the sample code is doing here? Well this extremely complex code is dynamically creating an account and then passing it. You can however retrieve an existing account and pass it as well. However here I am creating the account dynamically and passing it.

Simple piece of code. Hope this helps!

{KnowHow}–Authentication with Dynamics CRM online Web API without user login screen– Where headless authentication works and where not?

I have wrote blogs on how to execute call web-api from HTML page as well as Web Application sometime back. And while I truly appreciate the vast number of people writing back to me on how much they liked the blog, there were asks of how to acquire the access token seamlessly for Dynamics CRM Online, that is without user intervention.

For readers who are not aware of OAuth concepts and how it works in CRM perspective, please visit the below link.


The above post first gives you an introduction to the OAuth 2.0 protocol and then how to use that to connect to Dynamics CRM Web API endpoint from an external HTML Page. The post also covers on how to register the application in azure AD and get the client id and the client secret. Before you read further I would strongly suggest you go through the above post and understand how OAuth 2.0 works from CRM perspective.

So coming back to the topic, I put my head around a lot to get headless authentication from my web application but could not make it through. Basically, I was doing similar to what is mentioned in the below git-hub article, but somehow could not make it work from my web application. The git-hub mentions about the new ADAL library which introduces the classes for the headless authentication.


By chance one of the community discussions in Dynamics CRM group of facebook was discussing on a topic similar to this, I was directed to the original article on this topic


I carefully read through the entire post and finally after reading the limitations section I could understand why it is not working for my web application, although I am able to make it work from my WPF application or a simple c# console client.


First the positive one. How to make it work for native client applications. Below is the example for the same.

As a client I chose a C# console client. I registered my client in Azure AD and allowed implicit authorization in the manifest of the application. Also I allowed my application access to my Online Microsoft CRM instance. Getting bit confused about all this. You can always go back to the first link I shared in this post and understand. All these are explained in great details.

Everything is ready. So let’s get a bit dirty here with code.

Below is the code for my application. I am just retrieving the accounts and displaying the account names. CRM instance URL is – https://xrmtr20.crm.dynamics.com

static void Main(string[] args)
                     UserCredential userCredential = new UserCredential("<office 365 user name>", "<Office 365 Password>");
                     string authorityUri = "

                     TokenCache tokenCache = new TokenCache();

                     AuthenticationContext context = new AuthenticationContext(authorityUri);

                     AuthenticationResult result = context.AcquireToken("https://xrmtr20.crm.dynamics.com", "<client id obtained after registering with Azure AD>", userCredential);


              static void LoadAccounts(string accessToken)
                     var webRequest = (HttpWebRequest)WebRequest.Create(new Uri("
                     webRequest.Method = "GET";
                     webRequest.ContentLength = 0;
                     webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
                     webRequest.Headers.Add("OData-MaxVersion", "4.0");
                     webRequest.Headers.Add("OData-Version", "4.0");
                     webRequest.ContentType = "application/json; charset=utf-8";

                     using (var response = webRequest.GetResponse() as System.Net.HttpWebResponse)
                            //Get reader from response stream
                            using (var reader = new System.IO.StreamReader(response.GetResponseStream()))

                                   string responseContent = reader.ReadToEnd();

                                   dynamic dynamicObj = JsonConvert.DeserializeObject(responseContent);

                                   foreach (var data in dynamicObj.value)
                                          Console.WriteLine("Account: {0}", data.name.Value);


And these are the list of accounts.



Let’s explain the code a bit here. To use this code you have to add reference to Active Directory Authentication Library (ADAL) and then NewtonSoft.json.dll

In visual studio open Tools –> NuGet Package manager –> Package manage console


In the console, type the following command

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.7.10707.1513-rc –Pre

The package will be installed successfully. In the same way you can add reference to Newtonsoft.json.dll using the Nuget.

Once done, now its time to review the code.

The first improvement is the UserCredentials which has a provision for taking both the username and the password. The authorityuri in the code is basically the login screen of windows live to login to your dynamics crm application. If you carefully notice the URL here, it contains xrmtr20.onmicrosoft.com. This is the AD tenant you need to access to get the token.

Also the new ADAL API introduces new overloads of the AcquireToken.

public AuthenticationResult AcquireToken(string resource, string clientId, UserCredential userCredential);
public Task<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, UserCredential userCredential)


I have utilized both the above to get the access token. The remaining code just passes the access token to CRM to fetch the account data. Some mundane stuff.


Oh! So far so good and it works great with native client applications like WPF based application or C# console client. Unfortunately,  I was not able to make it work from my web application project. The area where I got stuck is, a web application project would need to use the client secret as well apart from the client id to get the access token and I could not find a overload of acquire token which would take the UserCredential object along with the client secret.

Just copying some of the limitations of headless authentication from one of the previous links I shared in this post. The content is as-is from the link.

Constraints & Limitations

Here there’s a list of limitations you’ll have to take into account when using this flow.

Only on .NET

Given the intended usage of this feature, we decided to add it only to .NET.

On Windows Store we added the ability to use Windows Integrated auth, which has many of the same advantages and less drawbacks. Details in another post.

No web sites/confidential clients

This is not an ADAL limitation, but an AAD setting. You can only use those flows from a native client. A confidential client, such as a web site, cannot use direct user credentials.


Microsoft accounts that are used in the context of an AAD tenant (classic example: Azure admins) cannot authenticate to AAD via raw credentials – they MUST use the interactive flow (though the PromptBehavior.Never flag remains an option).


Multi-factor authentication requires dynamic UX to be served on the fly – that clearly cannot happen in this flow.

No Consent

Users do not have any opportunity of providing consent if username & password are passed directly.

No multi-hop federation

Any scenario requiring home realm discovery, multiple federation hops and similar won’t work – the protocol steps are rigidly codified in the client library, with no chance for the server to dynamically influence the authentication path.

No any server side features, really

In the “traditional” AcquireToken flows you have the opportunity of injecting extra parameters that will influence the behavior of AAD – including parameters that AAD didn’t even support when the library was released. None of that is an option when using username and password directly.


I would be happy if someone can get this working for me.

Hope this helps!

{Workaround} Setting word templates using workflow not working for custom entity in Dynamics CRM 2016? Check this out

Document template feature of Dynamics CRM 2016 came as a big relief to many consultants like us whose only option prior to that was to go to customer and speak about mail merge and many a times which was not liked by customers much. However the introduction of word and excel template features in Dynamics CRM 2016 never ceases to amaze the customers and has made the life of consultants like us much easier.

Now coming to word templates, one big disadvantage while accomplishing from the CRM UI is that it cannot be done for multiple records. You have to do for each individual record which is quite cumbersome right?

Well you have a quick fix for that. There is a new step introduced in the workflow called Perform Action Step and using that you can actually set the word template for an entity. So basically the idea is you can have an on-demand workflow which will use this step to set the word template to the target entity type and then coming back to the UI, you can select multiple records and run the workflow. And your very complex workflow will attach the word template to each of the records you selected the workflow to run. You could view the the attachment in the annotations section for each record.






The above pics are taken from Inogic blog on the same article. It is a wonderful article which has explained the same approach that I highlighted above.  Just like all their other articles, this one is also a treat to read. – http://www.inogic.com/blog/2016/02/set-word-template-through-workflow-in-dynamics-crm-2016/

Well so far so good. But wait, are we missing a link here. Hell yeah!

All the examples you find on this topic are all using OOB entities and indeed all the examples work great. But to be honest, in most of the cases we end up designing lot of custom entities for the customer. So what if we need to do something similar for the custom entities. Well then you have a problem. Let’s explore that.

I have created a custom entity called Template Test. I created a global word template for the custom entity. Now I create a workflow of on-demand type which will set the word template to the custom entity as the target.

As usual, I select the Perform Action –> Set word template –> Click on Set properties –> Select the appropriate word template for the entity



Oops! What happened here? The problem here is that while selecting the target, the entity is not showing up in the Form Assistant like the one it shows for OOB entities like Account and Contact.


Scratching your head here to identify the issue. Well I have two solutions for you as a workaround for this and I leave this up to you to identify which one fits best for you


Sol 1: Enable Business Process Flows for the custom entity:

As weird it may sound, enabling business process flow for the custom entity would indeed make your entity appear in the form assistant for the target field.

Go to your entity customization and check the checkbox for business process flow fields creation.


Save and publish the entity customizations. Now come back to the workflow created earlier and click on the target field. You should be able to set it to the custom entity.


You actually do not need to create the business process flows for the entity. Just enabling it to support business process flows would do the trick for you.


Sol 2: Programmatically set the word template for your target entity

If the above solution is not your cup of tea, then you can do something like below:

  • Create a on-demand workflow for your custom entity which would invoke a custom workflow assembly.
  • The custom workflow assembly would set the word template programmatically using the below code.

OrganizationRequest req = new OrganizationRequest("SetWordTemplate");
req["Target"] = new EntityReference("<custom entity schema name>", customentityguid);
req["SelectedTemplate"] = new EntityReference("documenttemplate", templateid);

A small stuff but enough to waste your days researching on the same.


Hope this helps!

Parse SAML Assertion token generated from Dynamics CRM on-premise environment configured with Claims

This blog post is a continuation of my previous post in which I explained on how to get SAML Token programmatically for your Dynamics On-premise environment configured with claims. If you have not read the previous post, I strongly suggest to read it and come back to this.



In this blog post, I will show you how to read the SAML assertion token that was obtained in the previous step. This would be typically done by applications who are relying on your SAML token to authenticate the user and many cases would be handled by a separate. But knowing a bit more never really harms. So if you are interested, let’s proceed.

Our main intention here would be to parse the SAML token and get the user’s claims from that. But there is a problem here. The SAML assertion token would be encrypted by the certificate of your relying party. So the decrypting party would need to have the certificate to decrypt the SAML token. Just to give you an idea, the SAML assertion token would have the following format.

<samlp:Response ID=’_4172503e-7104-4382-8cda-6f93f65de530′ Version=’2.0′ IssueInstant=’2016-06-01T05:05:18.362Z’ Destination=https://SAMLAssertionendpoint” Consent=’urn:oasis:names:tc:SAML:2.0:consent:unspecified’ xmlns:samlp=’urn:oasis:names:tc:SAML:2.0:protocol’>
                              <Issuer xmlns=’urn:oasis:names:tc:SAML:2.0:assertion’>
/adfs/services/trust">http://<federation serverl url>/adfs/services/trust</Issuer>
                                <samlp:StatusCode Value=’urn:oasis:names:tc:SAML:2.0:status:Success’ />
                              <EncryptedAssertion xmlns=’urn:oasis:names:tc:SAML:2.0:assertion’>
                                <xenc:EncryptedData Type=’
http://www.w3.org/2001/04/xmlenc#Element’ xmlns:xenc=’http://www.w3.org/2001/04/xmlenc#’>
                                  <xenc:EncryptionMethod Algorithm=’
http://www.w3.org/2001/04/xmlenc#aes256-cbc’ />
                                  <KeyInfo xmlns=’
                                    <e:EncryptedKey xmlns:e=’
                                      <e:EncryptionMethod Algorithm=’
                                        <DigestMethod Algorithm=’
http://www.w3.org/2000/09/xmldsig#sha1′ />
                                        <ds:X509Data xmlns:ds=’
                                            <ds:X509IssuerName><—Removed certificate details—-></ds:X509IssuerName>


So let’s proceed with it.

  • Since Dynamics CRM is configured as your relying party, login to your Dynamics CRM server, open IIS –> Server Certificates –> Select the encryption certificate and right click – > select export option from the menu


  • Export it as .pfx file since you need the private key as well in the certificate to decrypt the SAML assertion. Since the certificate is exported as pfx file, you need to give a password here. Remember the password, this would be need later in code.


  • Click OK. The pfx file would be created in the location that you provided. Copy the .pfx file and store it in a location from  client application which consumes the SAML token, can access. The rest is very simple. Below is the sample code which would read the SAML assertion and get the claims back.


private static void SAMLParser()
                        string samlFilePath = @"saml.xml";
                        string certificatePath = @"<certificate path>.pfx";
                        X509Certificate2 cert = new X509Certificate2(certificatePath, "<password when exported>");
                        var serviceTokens = new List<SecurityToken>();
                        serviceTokens.Add(new X509SecurityToken(cert));

                        var issuers = new ConfigurationBasedIssuerNameRegistry();
                        issuers.AddTrustedIssuer(cert.Thumbprint, cert.IssuerName.Name);

                        var configuration = new SecurityTokenHandlerConfiguration
                                            AudienceRestriction = { AudienceMode = AudienceUriMode.Never },
                                            CertificateValidationMode = X509CertificateValidationMode.None,
                                            RevocationMode = X509RevocationMode.NoCheck,
                                            IssuerNameRegistry = issuers,
                                            MaxClockSkew = TimeSpan.FromMinutes(5),
                                            ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(serviceTokens.AsReadOnly(), false)


                        var tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);

                        using (StringReader sr = new StringReader(XDocument.Load(samlFilePath).ToString()))
                                using (XmlReader reader = XmlReader.Create(sr))
                                        if (!reader.ReadToFollowing("EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion"))
                                                throw new Exception("Assertion not found!");
                                        SecurityToken token = tokenHandlers.ReadToken(reader.ReadSubtree());

                                        Saml2SecurityToken samlToken = token as Saml2SecurityToken; // Getting the SAML token here.

                                        // This is where you get the claims of the user from the SAML assertion token

                                        Dictionary<string, object> payload = new Dictionary<string, object>();
                                        foreach (Saml2Statement statement in samlToken.Assertion.Statements)
                                                Saml2AttributeStatement attributeStatement = statement as Saml2AttributeStatement;
                                                if (null != attributeStatement)
                                                        foreach (Saml2Attribute attribute in attributeStatement.Attributes)
                                                                Console.WriteLine("Name: {0}, Value: {1} ValueType: {2}", attribute.Name, attribute.Values[0], attribute.AttributeValueXsiType);
                                                                payload.Add(attribute.Name, attribute.Values[0]);


                                    // Use this to convert it into JWT token and pass on to the web-api.


Since you are able to decrypt and find out the claims, you application assumes that it is being originated from your Dynamics CRM.

You can use these claims and then convert it into JWT token.


Hope this helps!

{Utility}–Get SAML Token programmatically for your Dynamics On-premise environment configured with claims

As a CRM Consultant we come across myriad of requirements. Of them some are our day-day stuffs. But the ones which puts us in a bit of head scratching and brainstorming are the ones which gives us the maximum satisfaction when completed. And this was one of them.

Our client had configured IFD for their Dynamics CRM 2015 on-premise environment. They had a WebAPI web service to which CRM needed to communicate. After initial discussions with the customer, the idea was to pass the SAML token from Dynamics CRM as one of header values in the web api call. The WebAPI would then parse the SAML token from the header of the request and then read the claims to authenticate the caller and send the response back to CRM.

So first things first. We have to pass the SAML token as one of the header values in the web-api call. How to approach this. Let’s understand the mechanism here. For people who already know this, it’s like a repeat but for readers who are unaware of this, I will try to put it in very simple terms.

  • CRM is configured as a relying party fro ADFS. So CRM will only trust only tokens generated from ADFS
  • User tries to login to Microsoft Dynamics CRM. Since user could not present a valid SAML token to CRM, CRM redirects the user to ADFS login page.
  • User enters the username and password. ADFS has active directory configured as trust store. It takes your userid and password and validates it against the identity provider which is your active directory.
  • IF the credentials are correct, Active directory issues a token which contains the claims for the user. ADFS then converts the claims and puts into the SAML token with the claims which are understood by your Dynamics CRM. The user now sends another request to Dynamics CRM and this time with a valid SAML token. CRM now allows the user login.


Believe me this is explained in a very simple way. However there are whole lot of stuffs that you need to configure for this to take place. If you are interested to know the gory details, you can visit the technet article – https://technet.microsoft.com/en-us/library/dn609803.aspx

Now coming back to our topic. Since our intention is to get the SAML token here, if we take an analogy, we have to replicate the whole process as above but without user intervention. Wait? What is the problem then? The problem the user’s credentials which needs to be passed to get the SAML token. How can we do this then?

The solution is to use execution users credentials and to do that we have to replicate the sign-in process. To do that the first thing make the user hit the SignOn page of ADFS.

The signon page has the url of https://<your adfs server url>/adfs/ls/idpinitiatedsignon.aspx

The next thing we need to do is create a SAML asserting endpoint for your relying party if that is already not present. To do this, follow the below steps

  • Open your ADFS server and then open ADFS Management window and click on relying parties.


  • Select the Relying Party trust for your CRM and then right click-> Properties  and go to EndPoints.


  • Check if you have SAML Assertion end-point showing up. If not then click on Add and enter a new SAML assertion end-point. Binding as POST and Assertion Endpoint with the same URL as your relying party.



  • Save and close out the Dialog.

Don’t worry. You ADFS configuration will not go wrong here. The Assertion end-point would work in conjunction with the WS-Federation end-points.

So that’s it you are all done. Now comes the coding part to get the SAML token. Well I have covered your back here. I have put the gory code into a managed solution and all you need to do is download the solution from the below codeplex link and then install it into your organization – https://crmsamlgenerator.codeplex.com/

Once installed, the following is the piece of code which you just need to write to get back your SAML assertion token.

OrganizationRequest samlInvoker = new OrganizationRequest();
samlInvoker.RequestName = "saml_SAMLInvoker";
samlInvoker.Parameters["IdpLoginPageUrl"] = “
/adfs/ls/idpinitiatedsignon.aspx";’>https://<federation server url>/adfs/ls/idpinitiatedsignon.aspx";
samlInvoker.Parameters["RelyingPartyUrl"] = "<Relying Party URL>";

var samlResponse = (OrganizationResponse)proxy.Execute(samlInvoker);

var samlParams = samlResponse.Results;

Console.WriteLine("SAML Token XML: {0}", samlParams["SamlTokenXml"]);


As you can see from the code above, all you need to do is invoke an action named “saml_SAMLInvoker” with the parameters I have mentioned before and you get the SAML token in XML format back. You call this from javascript too and get this token.

You can pass this to any any web-api call from javascript or server side call. A sample code for passing the SAML XML token in the header value is illustrated below.

_invokeWebAPI: function (samlToken) {
        var req = new XMLHttpRequest();
        req.open("GET", "<your web api query");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("SAML", samlToken);
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var discovery = JSON.parse(this.response);
                else {
                    var error = JSON.parse(this.response).error;

In my next article, I have explained how to parse the SAML Assertion token – https://debajmecrm.com/2016/06/06/parse-saml-assertion-token-generated-from-dynamics-crm-on-premise-environment-configured-with-claims/

Till then happy CRMing.