SPFx webpart consuming Yammer API using AadTokenProvider

4.3
(4)

Yammer JavaScript SDK gives you ability to consume Yammer Rest API. But the problem with the SDK is you need to handle the sign in through an iframe and a login button, so end users will have to click on that button and sign in to be able to use your app (if you are interested in building an SPFx web part using the Yammer Javascript SDK, you can see this sample on github).

Today I want to show you how you can use AadTokenProvider to overcome this problem, AadTokenProvider class gives you the ability to obtain OAuth2 tokens from Azure AD and after obtaining that token you can easily consume Yammer Rest API.

API permission

To get access to Yammer API, we need to add the required permission to “SharePoint Online Client Extensibility Web Application Principal” application:

  • Navigate to Azure portal.
  • Search for App Registration at top search box.
  • Select “SharePoint Online Client Extensibility Web Application Principal
  • Select “API permissions” from left navigation.
  • Click “Add a permission“.
  • Select Yammer.
  • Select “User_Impersonation” from delegated permissions.
  • Click “Add permissions“.
  • Click “Grant admin consent” button.
  • Select “Yes, add other granted permissions to configured permissions
  • Click “Save and continue“.
  • Click “Grant admin consent“.
  • Select “Yes“.

SPFx web part to post a praise to Yammer

If you are not familiar with creating a web part please first go through this post.

After creating the web part open it in an editor like Visual Studio Code, add OnInit method to your web part and add below code:

public async onInit(): Promise<void>{
    const tokenProvider:AadTokenProvider  = await this.context.aadTokenProviderFactory.getTokenProvider();
    await tokenProvider.getToken("https://api.yammer.com").then(token=>{
      this.aadToken = token;
    });
}

With getToken method we can get the jwt token for the specified resource which is api.yammer.com.

Now with that token you can easily communicate with Yammer API and do whatever you need to do. You can use your favourite library to do the CRUD operations (I’m using axios in this sample):

private readonly _apiUrl: string = "https://api.yammer.com/api/v1/";

private async getUserId(email: string) {
    
    const reqHeaders = {
        "Authorization": `Bearer ${this.aadToken}`
    };
    const result = await axios.get(`${this._apiUrl}users/by_email.json?email=${email}`,{headers:reqHeaders});
    return result.data[0].id;
}

public async getGroups(){

    const userId = await this.getUserId(this.currentUser);

    const reqHeaders = {
        "content-type": "application/json",
        "Authorization": `Bearer ${this.aadToken}`
    };

    return axios.get(`${this._apiUrl}groups/for_user/${userId}`, { headers: reqHeaders });

}

As you can see we only need to set the Authorization header with the token we got from the getToken method and then you can get what you need.

I provided a sample that posts a praise to Yammer, you can find the source code here.

We can go even further and add this web part to Microsoft Teams as Teams Tab, we just need to modify the manifest and update the supportedHost:

"supportedHosts": ["SharePointWebPart","TeamsTab","TeamsPersonalApp"]

You can give your app an icon which is under teams folder and you can replace it with your own icon.

After deploying your package to app catalog you can see “Sync to Teams” button in the ribbon, clicking that will upload the app manifest to Teams Apps which gives you options to add it as personal app or Teams Tab.

Open Microsoft Teams, from left side, select Apps, then select “Built for [your tenant name]“, and here you can find your app!

After adding the app, you will be able to open it as personal app or add it to a team:

Access AAD secured endpoint not working on Teams Tab

You may face this issue when trying to use AadHttpClient or AadTokenProvider class to get access to a secured endpoint like api.yammer.com.

To solve this problem:

  • Go to Azure portal.
  • Go to App Registrations.
  • Select “SharePoint Online Client Extensibility Web Application Principal“.
  • Select Manifest from left navigation.
  • Click Download.
  • Open the manifest.
  • Copy the id from the oAuth2Permission array.
  • Replace “preAuthorizedApplications” entry with the following json.
"preAuthorizedApplications": [
	{
		"appId": "00000003-0000-0ff1-ce00-000000000000",
		"permissionIds": [
			"7b30d829-354d-43b6-89f7-1f6ff27129d9"
		]
	}
]
  • Replace PermissionIds with the Id from last step.
  • Save the file.
  • Upload the manifest.
  • Click Save.

It takes a while so you can see the result so give it some time.

Summary

Using AadTokenProvider makes your life as developer a lot easier as you don’t have to write more lines of code in order to cosume an API, also users don’t need to login again by clicking on a button as they have already signed in to SharePoint.

Also using SharePoint Framework you can easily develop Microsoft Teams Tab without being worry about hosting, deployment and upgrading your app.

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 4

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

Leave a Reply

Your email address will not be published. Required fields are marked *