Connection to CRM Organization with Python

Connecting to a CRM organization and securely accessing its data can sometimes be a complex task. In this blog post, we will explore a Python script that leverages Microsoft Azure Active Directory and OAuth 2.0 authentication to streamline the process of connecting to a CRM organization. By the end, you’ll have a clear understanding of how to authenticate and obtain an access token, enabling you to interact with CRM data effortlessly.

What is OAuth 2.0

Lets start with the basics for this task: What actually is OAuth?
OAuth 2.0 is an open standard framework for authorization that allows users to grant limited access to their protected resources on one website to another website or application without sharing their credentials. It is widely used as a security protocol for enabling secure access to APIs and web services.

The key components of OAuth 2.0 are:

  1. Resource Owner: The resource owner is the user who owns the protected resources (e.g., personal data, photos, documents) and grants access to those resources to other applications or services.
  2. Client: The client is the application or service that requests access to the protected resources on behalf of the resource owner. It can be a web application, a mobile app, or a server-based application.
  3. Authorization Server: The authorization server is responsible for authenticating the resource owner and issuing access tokens after obtaining authorization. It verifies the identity of the client and the resource owner and ensures that the requested permissions are valid.
  4. Resource Server: The resource server hosts the protected resources that the client wants to access. It verifies the access tokens received from the client and grants access to the requested resources if the token is valid and authorized.
  5. Access Token: An access token is a credential issued by the authorization server to the client after successful authentication and authorization. The client presents this token to the resource server to gain access to the protected resources.

The OAuth 2.0 flow typically involves the following steps:

  1. Client Registration: The client (application) registers with the authorization server, providing details such as client ID, client secret, and redirect URIs. This allows the authorization server to identify and authenticate the client.
  2. Authorization Request: The client initiates the authorization process by redirecting the resource owner to the authorization server. The request includes parameters such as client ID, requested scope, and redirect URI.
  3. User Authentication and Consent: The resource owner is prompted to authenticate themselves on the authorization server. Once authenticated, they are presented with a consent screen that outlines the requested permissions. The resource owner can either grant or deny access to their protected resources.
  4. Authorization Grant: If the resource owner grants access, the authorization server issues an authorization grant to the client. The grant could be in the form of an authorization code, an implicit token, or another grant type, depending on the chosen OAuth 2.0 flow.
  5. Access Token Request: The client sends a request to the authorization server, including the authorization grant received in the previous step. Additionally, the client authenticates itself by providing its client ID and client secret.
  6. Access Token Response: Upon successful verification of the authorization grant and client credentials, the authorization server responds with an access token and, optionally, a refresh token. The access token represents the authorization to access the protected resources.
  7. Accessing Protected Resources: The client presents the access token to the resource server when requesting access to protected resources. The resource server verifies the access token’s validity and scope and grants or denies access accordingly.
  8. Token Refresh (optional): If the access token expires, the client can request a new one using the refresh token provided by the authorization server during step 6. This allows the client to continue accessing resources without requiring the resource owner’s interaction.

OAuth 2.0 provides a flexible and secure mechanism for granting access to protected resources without sharing passwords or credentials. It enables seamless integration between applications and services while maintaining user privacy and control over their data.

Prerequisites

Before connecting to your Dynamics CRM environment, there are a few prerequisites that need to be fulfilled. Firstly, you need to create an application user within the CRM organization. This involves setting up a user account specifically for the application or service that will be accessing the CRM data. To do so, you must have a registered application in Microsoft Azure Active Directory (Azure AD). This registration establishes the necessary credentials, such as the client ID and client secret, which are used to authenticate and authorize the application user when connecting to the CRM organization. The Azure AD registration ensures secure and controlled access to the CRM data and allows for seamless integration between the application user and the CRM system. The Application Registration will need permissions to read the D365 Data and Admin Consent will need to be granted.

Connecting to the CRM Organization

After registering an application within Azure AD, we gain the ability to authenticate and authorize access on behalf of the application user. Let’s break down the key steps of the script:

import requests

def authenticate():
    crmorg = 'https://YOUR_ORG.api.crm4.dynamics.com' #base url for crm org  
    clientid = 'YOUR_APPLICATION_ID' #application client id  
    clientsecret = 'YOUR_APPLICATION_ID'

    tokenendpoint = 'https://login.microsoftonline.com/YOUR_TENANTID/oauth2/token' #oauth token endpoint
    tokenpost = {  
        'client_id':clientid,
        'resource':crmorg,
        'client_secret':clientsecret,
        'grant_type':'client_credentials'
    }

    tokenres = requests.post(tokenendpoint, data=tokenpost)
    accesstoken = ''
    try:  
        accesstoken = tokenres.json()['access_token']
    except(KeyError):  
        print('Could not get access token')
    return accesstoken

authenticate()
  1. The authenticate() function is defined to handle the authentication process.
  2. The crmorg variable is set to the base URL of the CRM organization you want to connect to. Make sure to replace 'YOUR_ORG' with the appropriate value.
  3. The clientid variable is set to the client ID of your application. Replace 'YOUR_APPLICATION_ID' with the actual client ID obtained from the CRM organization.
  4. The clientsecret variable is set to the client secret of your application. Replace 'YOUR_APPLICATION_ID' with the actual client secret obtained from the CRM organization.
  5. The tokenendpoint variable is set to the OAuth token endpoint provided by Microsoft Azure Active Directory. Replace 'YOUR_TENANTID' with the appropriate value.
  6. The tokenpost dictionary is created to contain the parameters required for the token request. It includes the client ID, resource (CRM organization URL), client secret, and grant type set to 'client_credentials'.
  7. The requests.post() function is used to send a POST request to the token endpoint with the tokenpost data.
  8. The response from the token request is stored in the tokenres variable.
  9. The access_token variable is initialized as an empty string.
  10. A try-except block is used to extract the access token from the response. If the response contains an 'access_token' key, the value is assigned to accesstoken. Otherwise, it prints a message indicating that the access token could not be obtained.
  11. The access_token is returned by the authenticate() function.

Conclusion

Connecting to a CRM organization and accessing its data is made easier with the Python script we explored in this blog post. By leveraging Microsoft Azure Active Directory, OAuth 2.0, and Azure Functions, you can streamline the authentication process, obtain an access token, and establish a secure connection. This empowers you to interact with CRM data efficiently and

Leave a comment