如何获取具有通道消息发送权限的ms graph api访问令牌

问题描述 投票:0回答:1

我正在尝试将自适应卡从 React 应用程序发送到 MS 团队频道。我已向应用程序注册中创建的应用程序授予“ChannelMessage.Send”权限。以下是从 Postman 复制的代码:

var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
  'client_id': 'xxx',
  'scope': 'https://graph.microsoft.com/.default',
  'client_secret': 'xxx',
  'grant_type': 'client_credentials' 
});
var config = {
  method: 'post',
  url: 'https://login.microsoftonline.com/xxx/oauth2/v2.0/token',
  headers: { 
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

但是,返回的访问令牌仅具有以下作用:

"roles": [
    "User.Read.All"
  ],

如果我使用此令牌发送消息,我会收到“禁止”错误。如何获取正确的访问令牌以将消息发送到团队频道?我尝试了以下范围,但都无效。

https://graph.microsoft.com/.default+ChannelMessage.Send https://graph.microsoft.com/.default ChannelMessage.Send

microsoft-graph-api microsoft-teams
1个回答
0
投票

前面的响应中提供的代码用于使用客户端凭据流获取访问令牌,适用于服务器到服务器的通信。但是,要将消息发送到 Teams 频道,您需要使用发送消息的用户的用户令牌。

要获取用户令牌,您可以在 React 应用程序中使用适用于 JavaScript 的 Microsoft 身份验证库 (MSAL)。以下是如何获取用户令牌的示例:

import { PublicClientApplication } from '@azure/msal-browser';

const msalConfig = {
  auth: {
    clientId: 'YOUR_CLIENT_ID',
    redirectUri: 'http://localhost:3000', // Replace with your app's redirect URI
  },
};

const msalInstance = new PublicClientApplication(msalConfig);

// Request the necessary scopes
const loginRequest = {
  scopes: ['ChannelMessage.Send'],
};

// Sign in the user and obtain the token
msalInstance.loginPopup(loginRequest)
  .then((response) => {
    // Access token is available in response.accessToken
    console.log(response.accessToken);
  })
  .catch((error) => {
    console.log(error);
  });

获得用户令牌后,您可以使用它通过 Microsoft Graph API 将消息发送到 Teams 频道。以下是如何使用 axios 库发送消息的示例:

const accessToken = 'USER_ACCESS_TOKEN'; // Replace with the user access token

const message = {
  body: {
    content: 'Hello from my app!',
  },
};

axios.post('https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/messages', message, {
  headers: {
    Authorization: `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
© www.soinside.com 2019 - 2024. All rights reserved.