5
(1)

We usually building a SharePoint Framework solution that requires access to specific resources secured with Azure AD such as Microsoft Graph, Yammer, and Dynamic CRM. In this post I will show you how you can consume Dynamics CRM API from an SPFx web part.

Dynamics 365 30-day Trial

If you don’t already have a Dynamics 365 environment, you can sign up for a 30-day trial from here.

API permissions

To be abe to obtain the access token from our web part we need to add required permissions to the app registration, you can either create an app registration, add your permissions to it and use AadHttpClient to use the resources or you can add the permissions directly to the SharePoint Online Client Extensibility Azure AD application and use the AadTokenProvider class to obtain the access token.

In this sample I add the “Dynamics CRM” to the SharePoint Online Client Extensibility Azure AD application:

App Registration Manifest

Go to the manifest page, and makes sure the value for the allowPublicClient and the oauth2AllowImplicitFlow is set to true.

Obtain Access Token

In your code, you can use AadTokenProviderFactory class to get the access token:

public async getAccessToken(){
    const token = sessionStorage.getItem("dynamic365Token");
    if(token)
      this.accessToken = token;
    else{
      await 
      this.aadTokenProviderFactory
      .getTokenProvider()
      .then((tokenProvider) => {
        tokenProvider
          .getToken(this.resourceUri)
          .then((t) => {
            this.accessToken = t;
            sessionStorage.setItem("dynamic365Token",t);
          })
          .catch((err) => console.log("Error: " + err));
      });
    }
  }

The resource URI in the above code would be your company’s CRM URI (e.x., https://contoso.crm11.dynamics.com). You can also keep the token in the session storage or local storage to not get a new one each time the page gets refreshed.

Consume the API

After obtaining the access token you can consume the API like this:

public async getAccounts() {
    const url = `${this.resourceUri}/api/data/v9.0/accounts?$top=20&$select=name,emailaddress1`;
    const response = await axios({
      url,
      method: "GET",
      headers:{"Authorization":`Bearer ${this.accessToken}`}
    });
    return response.data.value;
}

In above sample, I’m getting the accounts from the Dynamic 365 Sales.

I provide you a sample that displays accounts and relate contacts from Dynamic CRM which you can find the source code here.

Summary

What we have seen above is a simple SharePoint Framework web part which consumes Dynamics CRM API. We used the AadTokenProvider class to obtain the OAuth2 token which is used to authenticate the user from the SharePoint page to a service like Dynamics CRM.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.