Using Graph API to Send Messages in a "One-to-One" Teams Chat from an ASP .Net Core Application

Carsten Cors 0 Reputation points
2024-08-12T05:38:04.7166667+00:00

Hello Microsoft Team,

I have the following goal: We want to send a message in a "One-to-One" Teams chat from an ASP .Net Core application. For this, we intended to use the Graph API and have created the following example based on the documentation:

Code Example:


using Azure.Identity;
using Microsoft.Graph.Models;
using Microsoft.Identity.Client;

namespace TeamsExampel
{
    public class TestTeamsMessage
    {
        private string TENANT_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        private string APP_CLIENT_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        private string APP_CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        private string SERVICEACCOUNT = "******@anaxco.de";

        public async Task SendTeamsMessage()
        {
            await SendMessageAsync("******@anaxco.de", "This is a test message");
        }

        private async Task<object> SendMessageAsync(string receiverEmail, string message)
        {
            var scopesChat = new List<string> { "https://graph.microsoft.com/.default" };
            var options = new ClientCertificateCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            try
            {
                var clientSecretCredential = new ClientSecretCredential(TENANT_ID, APP_CLIENT_ID, APP_CLIENT_SECRET, options);
                var graphClient = new Microsoft.Graph.GraphServiceClient(clientSecretCredential, scopesChat);

                var userReceiver = await graphClient.Users[receiverEmail].GetAsync();
                var userService = await graphClient.Users[SERVICEACCOUNT].GetAsync();

                if (userReceiver == null)
                {
                    return $"User {receiverEmail} not found.";
                }

                var newChat = new Chat
                {
                    ChatType = ChatType.OneOnOne,
                    TenantId = TENANT_ID,
                    Members = new List<ConversationMember>
             {
                 new AadUserConversationMember
                 {
                     TenantId= TENANT_ID,
                     UserId =userService.Id,
                     Roles = new List<string> { "owner" },
                     AdditionalData = new Dictionary<string, object>
                     {
                         {
                             "******@odata.bind" , $"https://graph.microsoft.com/v1.0/users('{userService.Id}')"
                         },
                     },
                 },
                 new AadUserConversationMember
                 {
                     TenantId= TENANT_ID,
                     UserId= userReceiver.Id,
                     Roles = new List<string> { "owner" },
                     AdditionalData = new Dictionary<string, object>
                     {
                         {
                             "******@odata.bind" , $"https://graph.microsoft.com/v1.0/users('{userReceiver.Id}')"
                         },
                     },
                 }
             },
                };

                var createdChat = await graphClient.Chats.PostAsync(newChat);

                ChatMessage msg = new ChatMessage()
                {
                    CreatedDateTime = DateTime.Now,
                    ChatId = createdChat.Id,
                    From = new ChatMessageFromIdentitySet
                    {
                        User = new Identity
                        {
                            Id = userService.Id,
                            DisplayName = userService.DisplayName,
                        }
                    },
                    MessageType = ChatMessageType.Message,
                    Body = new ItemBody
                    {
                        ContentType = BodyType.Html,
                        Content = message
                    }
                };


                var chatresult = await graphClient.Chats[createdChat.Id].Messages.PostAsync(msg);

                return chatresult;
            }
            catch (Exception ex)
            {
                return ex;
            }
        }
    }
}

Permissions:

We have configured the ASP .Net Core application with the appropriate Application permissions according to the documentation.

User's image

Error Message:

We are receiving the following error message when we run the code:
HTTP Status Code 403, InsufficientPrivileges
User's image

We’ve been unable to create a working example based on the documentation. We would greatly appreciate your assistance in resolving this issue.

Thank you in advance!

Developer technologies | ASP.NET | ASP.NET Core
Microsoft Security | Microsoft Graph
Microsoft Teams | Microsoft Teams for business | Other
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 46,371 Reputation points
    2024-08-12T06:03:06.0433333+00:00

    Hi @Carsten Cors

    Application permissions are typically used for data migration (importing messages from third-party platforms) rather than sending messages.

    To send messages, you should use delegated permissions instead.

    a3516111-0d13-4b79-b6e4-f809a4938124

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.