0

Not able to post message in teams chat using Graph API in SPFX using Token but able to get chats by using token

Getting error in console Requested API is not supported in application-only context

Given all the permission for delegated type for send and create chats still getting same error

Able to fetch all the request but not able to Post Request with this Access_token

I think token not able to use delegated permission , Is there any other way to get token for delegated permissions

Code for Access_Token in Graph API

$.ajax({
        "async": true,
        "crossDomain": true,
        "url":  "https://howling-crypt-47129.herokuapp.com/https://login.microsoftonline.com/adaptindia.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie  
        "method": "POST",
        "headers": {
            "Authorization": "Bearer",
        "Content-Type": "application/x-www-form-urlencoded"
        },
        "data": {
            "grant_type": "client_credentials",
            "client_id": "", //Provide your app id
             "client_secret": "", //Provide your secret  
             "scope": "https://graph.microsoft.com/.default",     
            
      
        },
        success: (response) =>{
          console.log(response);
          token = response.access_token;
        }
  })

1 Answer 1

1

I built a SPFx web part and I was able to both read and post Teams chat messages when I requested ChannelMessage.Read.All and ChannelMessage.Send.

Here are links to the documentation for the Microsoft Graph requests I used.

List channel messages

Send chatMessage in a channel or a chat

Here is the package-solution.json file I used. The webApiPermissionRequests property defines the requests for the ChannelMessage.Read.All and ChannelMessage.Send delegated permissions.

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
  "solution": {
    "name": "spfx-teams-chat-client-side-solution",
    "id": "253c0d28-fdd4-4ca0-b5f1-b2b6c8d71449",
    "version": "1.1.0.0",
    "includeClientSideAssets": true,
    "skipFeatureDeployment": true,
    "webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "ChannelMessage.Read.All"
      },
      {
        "resource": "Microsoft Graph",
        "scope": "ChannelMessage.Send"
      }
    ],
    "isDomainIsolated": false,
    "developer": {
      "name": "",
      "websiteUrl": "",
      "privacyUrl": "",
      "termsOfUseUrl": "",
      "mpnId": "Undefined-1.14.0"
    },
    "metadata": {
      "shortDescription": {
        "default": "SpfxTeamsChat description"
      },
      "longDescription": {
        "default": "SpfxTeamsChat description"
      },
      "screenshotPaths": [],
      "videoUrl": "",
      "categories": []
    },
    "features": [
      {
        "title": "spfx-teams-chat Feature",
        "description": "The feature that activates elements of the spfx-teams-chat solution.",
        "id": "50c11104-f9b1-4c99-a5ce-267fdfc0eebe",
        "version": "1.0.0.0"
      }
    ]
  },
  "paths": {
    "zippedPackage": "solution/spfx-teams-chat.sppkg"
  }
}

Here is the code for the render() method of the web part along with the method it calls to add the messages to the channel. This code uses the MSGraphClient type to make calls to Microsoft Graph. The MSGraphClient handles authentication with Azure AD and retrieving the access token for you.

public render(): void {
  this.domElement.innerHTML = `
  <section class="${styles.spfxTeamsChat} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
    <div>
      <ul id="chatMessagesList">
      </ul>
    </div>
    <div>
      <button type="button" id="addChatMessageButton">Add chat message</button>
    </div>
  </section>`;

  this.context.msGraphClientFactory.getClient()
    .then((client: MSGraphClient): void => {
      let graphChannelMessagesUrl = `https://graph.microsoft.com/v1.0` +
        `/teams/${this.teamId}` +
        `/channels/${this.channelId}` +
        `/messages`;

      client.api(graphChannelMessagesUrl)
        .get((error: any, response: any, rawResponse?: any) => {
          let listContainer = this.domElement.querySelector("#chatMessagesList");
          let messages: MicrosoftGraph.Message[] = response.value;
          messages.forEach((message) => {
            if (message.body && message.body.content && message.body.content.trim().length > 0) {
              listContainer.innerHTML += `<li>${message.body.content}</li>`;
            }
          });

          let webPart: SpfxTeamsChatWebPart = this;
          let button: Element = this.domElement.querySelector("#addChatMessageButton");
          button.addEventListener("click", () => { webPart.addChatMessageButtonClickHandler(); });
        });
    });
}

private addChatMessageButtonClickHandler(): void {
  this.context.msGraphClientFactory.getClient()
    .then((client: MSGraphClient): void => {
      let graphChannelMessagesUrl = `https://graph.microsoft.com/v1.0` +
        `/teams/${this.teamId}` +
        `/channels/${this.channelId}` +
        `/messages`;

      let message: MicrosoftGraph.Message = {
        body: {
          content: "From SPFx"
        }
      };

      client.api(graphChannelMessagesUrl)
        .post(message)
        .then((response: any) => {
          debugger;
          this.render();
        })
        .catch((response: any) => {
          debugger;
        });
    });
}

The supportedHosts property in the manifest for the web part indicates that it may be used as a SharePoint web part, in a Teams tab, or in a Teams personal app.

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
  "id": "370255fa-598b-48ed-8237-6888f84c318c",
  "alias": "SpfxTeamsChatWebPart",
  "componentType": "WebPart",
  "version": "*",
  "manifestVersion": 2,
  "requiresCustomScript": false,
  "supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
  "supportsThemeVariants": true,

  "preconfiguredEntries": [{
    "groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
    "group": { "default": "Other" },
    "title": { "default": "SpfxTeamsChat" },
    "description": { "default": "SpfxTeamsChat description" },
    "officeFabricIconFontName": "Page",
    "properties": {
      "description": "SpfxTeamsChat"
    }
  }]
}

For more information on consuming Microsoft Graph from an SPFx web part, please see: Consume the Microsoft Graph in the SharePoint Framework.

For more information on using an SPFx web part in a Teams tab, please see: Build Microsoft Teams tab using SharePoint Framework - Tutorial

4
  • Yes, able to do in that same way but want to make a Graph API call using AJAX by passing Access token as a parameter so that web part can be used in Microsoft teams website Tab and I am able to fetch teams chats messages using AJAX call by using Access token but not able to make Post request in teams chats using token getting error - Requested API is not supported in application-only context Given all the permission in Azure APP for sending messages in teams chat Apr 18, 2022 at 7:48
  • 1
    I think it would help people assist you if you could edit your question to provide some additional detail (perhaps with some screen captures and/or code snippets). For example - How are you getting the access token? What permissions does the token have? Are the permissions delegated or application permissions? Apr 18, 2022 at 11:09
  • Please see the updated question , I think my request token is not able to use Delegated permission for Graph API post request Apr 18, 2022 at 13:05
  • I updated my answer to provide additional information about how to call Microsoft Graph from an SPFx web part using delegated permissions and how to use an SPFx web part as a Teams tab. I hope this will clear up any confusion. Apr 18, 2022 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.