{"id":37403,"date":"2024-02-10T17:43:58","date_gmt":"2024-02-10T12:13:58","guid":{"rendered":"https:\/\/techmasala.addastudents.com\/dev\/?p=37403"},"modified":"2024-02-10T17:44:00","modified_gmt":"2024-02-10T12:14:00","slug":"how-to-call-azure-functions-from-dynamics-365-crm-plugins","status":"publish","type":"post","link":"https:\/\/techmasala.addastudents.com\/dev\/how-to-call-azure-functions-from-dynamics-365-crm-plugins\/","title":{"rendered":"How to Call Azure Functions from Dynamics 365 CRM Plugins"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Expanding the capabilities of Dynamics 365 CRM requires seamless integration with external services. Azure Functions, with their serverless architecture and diverse functionalities, offer an ideal solution. This article guides you through calling Azure Functions from Dynamics 365 CRM plugins while incorporating secure token-based authentication, ensuring enhanced security and control.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Prerequisites:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Dynamics 365 CRM instance<\/li>\n\n\n\n<li>Active Azure subscription with Function App (HTTP-triggered function)<\/li>\n\n\n\n<li>Basic understanding of Dynamics 365 plugin development<\/li>\n\n\n\n<li>Azure Active Directory (AAD) app registered with Microsoft Graph API permissions<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Steps:<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>1. Configure AAD App and Permission:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Access the Azure portal and navigate to Azure Active Directory.<\/li>\n\n\n\n<li>Click &#8220;App Registrations&#8221; and register a new Web app\/API application.<\/li>\n\n\n\n<li>Note down the Application (client) ID and Secret generated.<\/li>\n\n\n\n<li>Under &#8220;API permissions,&#8221; add &#8220;Microsoft Graph&#8221; and grant appropriate delegated permissions (e.g.,&nbsp;user.read,&nbsp;offline_access).<\/li>\n\n\n\n<li>Expose an API URL to access the registered app&#8217;s permissions (e.g.,&nbsp;&lt;invalid URL removed&gt;).<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>2. Acquire Access Token in the Plugin:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In your Dynamics 365 plugin code,&nbsp;leverage the C#&nbsp;<code class=\"\">XrmTooling.Connector<\/code>&nbsp;library to establish a connection.<\/li>\n\n\n\n<li>Utilize the&nbsp;<code class=\"\">ExecuteAsync<\/code>&nbsp;method of the&nbsp;<code class=\"\">Client<\/code>&nbsp;class,&nbsp;passing the Organization service URI and user credentials.<\/li>\n\n\n\n<li>Construct the OAuth 2.0 authorization request URL with:\n<ul class=\"wp-block-list\">\n<li><code class=\"\">resource<\/code>&nbsp;parameter set to the Dynamics 365 CRM instance URL (e.g.,&nbsp;<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/your-org.crm.dynamics.com\/\">https:\/\/your-org.crm.dynamics.com<\/a>)<\/li>\n\n\n\n<li><code class=\"\">client_id<\/code>&nbsp;as your AAD app&#8217;s client ID<\/li>\n\n\n\n<li><code class=\"\">client_secret<\/code>&nbsp;as your AAD app&#8217;s secret<\/li>\n\n\n\n<li><code class=\"\">grant_type<\/code>&nbsp;set to&nbsp;<code class=\"\">client_credentials<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Send an HTTP POST request to the constructed URL and parse the JSON response to extract the access token.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example (C# snippet to generate token):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static string GenerateAccessToken()\n    {\n        try\n        {\n            string azureFunctionToken = string.Empty;\n                string tenantId = \"Your_Tenant_ID_URL\";\n                string clientId = \"Your_Client_ID\";\n                string clientSecret = \"Your_Client_Secret\";\n                string resource = \"Your_Resource\"; \/\/ Resource identifier\n                string grantType = \"client_credentials\";\n\n            \/\/ Azure AD token endpoint\n            var tokenEndpoint = \"https:\/\/login.microsoftonline.com\/\" + tenantId + \"\/oauth2\/token\";\n\n            using (var webClient = new WebClient())\n            {\n                \/\/ Construct parameters for token request\n                var parameters = new NameValueCollection();\n                parameters.Add(\"client_id\", clientId);\n                parameters.Add(\"client_secret\", clientSecret);\n                parameters.Add(\"resource\", resource);\n                parameters.Add(\"grant_type\", grantType);\n\n                \/\/ Send token request and receive response\n                var responseTokenBytes = webClient.UploadValues(tokenEndpoint, \"POST\", parameters);\n                string responseTokenContent = Encoding.UTF8.GetString(responseTokenBytes).Replace(@\"\\\", \"\");\n\n                \/\/ Deserialize response to access token object\n                var azureFunctionTokenResponse = responseTokenContent.Deserialize&lt;AzureFunctionTokenResponseBase>();\n                azureFunctionToken = azureFunctionTokenResponse.access_token;\n\n                \/\/ Return the access token\n                return azureFunctionToken;\n            }\n        }\n        catch (Exception ex)\n        {\n            \/\/ Handle any exceptions\n            Console.WriteLine(\"Exception Error: \" + ex.Message);\n            throw;\n        }\n    }\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>3. Call Azure Function with Token:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In your plugin code,&nbsp;prepare the data you want to send to the Azure Function (e.g.,&nbsp;serialize into JSON).<\/li>\n\n\n\n<li>Create an&nbsp;<code class=\"\">HttpClient<\/code>&nbsp;object and set the&nbsp;<code class=\"\">Authorization<\/code>&nbsp;header with the Bearer token you obtained.<\/li>\n\n\n\n<li>Use the\u00a0<code class=\"\">HttpPostAsync<\/code>\u00a0method <code class=\"\">HttpClient<\/code>\u00a0to send the data to your Azure Function&#8217;s HTTP trigger URL.<\/li>\n\n\n\n<li>Ensure the Azure Function is configured to validate the provided token using AAD authentication and handle the received data accordingly.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example (C# snippet to call Azure Function):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> \/\/ Method to call Azure Function\n        public static string CallAzureFunction()\n        {\n            try\n            {\n                \/\/ Prepare request data\n                var req = new {};\n\n                \/\/ Azure Function endpoint URL\n                string requestUri = \"Your_Azure_Function_URL\";\n\n                \/\/ Get access token for authorization\n                var accessToken = AccessTokenGenerator();\n\n                \/\/ Prepare request object\n                HttpResponseMessage response = new HttpResponseMessage();\n                string serializedRequest = JsonConvert.SerializeObject(req);\n                var method = new HttpMethod(\"POST\");\n                var requestObj = new HttpRequestMessage(method, requestUri);\n\n                \/\/ Set request headers\n                requestObj.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application\/json\"));\n                requestObj.Headers.Authorization = new AuthenticationHeaderValue(\"Bearer\", accessToken);\n\n                \/\/ Set request content\n                requestObj.Content = new StringContent(serializedRequest, Encoding.UTF8);\n                requestObj.Content.Headers.ContentType = new MediaTypeHeaderValue(\"application\/json\");\n\n                \/\/ Send request and receive response\n                HttpClient httpClient = new HttpClient();\n                response = httpClient.SendAsync(requestObj).GetAwaiter().GetResult();\n                string responseText = response.Content.ReadAsStringAsync().Result;\n\n                \/\/ Return response\n                return responseText;\n            }\n            catch (Exception ex)\n            {\n                \/\/ Handle any exceptions\n                Console.WriteLine(\"Exception Error: \" + ex.Message);\n                throw;\n            }\n        }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Remember:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Store sensitive information like the AAD app secret securely using encrypted configuration options within Dynamics 365 CRM.<\/li>\n\n\n\n<li>Handle errors gracefully in both plugin and Azure Function code,&nbsp;implementing retry mechanisms if necessary.<\/li>\n\n\n\n<li>Consider using Managed Identity for Azure Functions for seamless token acquisition without managing secrets directly in the code.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">By following these steps and adapting them to your specific requirements, you can securely call Azure Functions from Dynamics 365 CRM plugins, unlocking powerful integrations and enhancing your automation capabilities.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Expanding the capabilities of Dynamics 365 CRM requires seamless integration with external services. Azure Functions, with their serverless architecture and diverse functionalities, offer an ideal solution. This article guides you through calling Azure Functions from Dynamics 365 CRM plugins while incorporating secure token-based authentication, ensuring enhanced security and control. Prerequisites: Steps: 1. Configure AAD App [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":37410,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"footnotes":""},"categories":[70,17,72],"tags":[892,891,772],"class_list":["post-37403","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-learn-technology-free","category-learn-microsoft-dynamics-crm","category-tech","tag-automation","tag-dynamics-365-crm","tag-integration"],"_links":{"self":[{"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/posts\/37403","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/comments?post=37403"}],"version-history":[{"count":6,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/posts\/37403\/revisions"}],"predecessor-version":[{"id":37409,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/posts\/37403\/revisions\/37409"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/media\/37410"}],"wp:attachment":[{"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/media?parent=37403"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/categories?post=37403"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techmasala.addastudents.com\/dev\/wp-json\/wp\/v2\/tags?post=37403"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}