Audience targeting custom SPFx webpart

16 Apr

A lot of standard SharePoint webparts have the ability to use audience targeting. Audience targeting can be used to promote content to specific audiences across the site using Microsoft Entra ID groups (formerly knows as Azure Active Directory groups).

This post is about to use the same audience targeting on custom SPFx webparts.

Lets take the standard SharePoint news web part as an example. Audience targeting has to be enabled for the pages library that contains the news pages as well at the news web part itself. At the page level the appropriate audiences can be selected.

After creating some news pages with audiences set the news web part will show different news to different audiences.

Example

To show how audiences can be implemented in a custom SPFx web part we’ll create a simple example.
Certain data is stored in a list that needs to be displayed to different target groups through a web part. First a list has to be created with Audience targeting enabled.

Second a web part has to be created using Yeoman as you would do with any other web part creation.

In the webpart the list is queried. To check the fields returned regarding the audience on the list item the following statement is used

const listItems: any[] = await this._sp.web.lists.getById(listGuid)
                .items();

The result was not the guid of the audience set, but the id of the audience in the User Information List.

This audience guid can be made visible in the listview by selecting the field AudienceIds, unfortunately the guid wasn’t returned calling ‘.items()’.

By using search to query the list the AudienceId can be returned

Now the audienceId has to match one of the groups of the user to be able to determine if the item can be shown to the user.

In my opinion there a two options to accomplish the match between the audienceId of the item and the groupIds of the user:

  1. Use the Graph API to query the groupIds of the user
  2. Use a result source when performing the search

Graph API

By using the Graph API a call has to be made to ‘me/transitiveMemberOf/microsoft.graph.group’. This results all the groups the user is a direct or indirect member of. After the call the audienceId of the item has will have to be looked up in the groups of the user.

Expanding Search

The search query can be expanded with a result source to match the audienceId of the item with the groupIds of the user. The content of the result source is:

{searchTerms} AND ModernAudienceAadObjectIds:{User.Audiences}

The search setting with SourceId of the result source:

Final thought

This example shows you how to implement Audience targeting on list content, while the SPFx component takes this Audience setting into account: the component shows the content to the right users.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.