Pravin Durgam
Pravin Durgam

Reputation: 127

Getting Forbidden error while posting the message in Microsoft teams general channel via Microsoft Graph API in C#

I am trying to post the message in the Microsoft Teams in general channel via Microsoft Graph API using C# code but getting below error:

Code: Forbidden Message: Forbidden Inner error: AdditionalData: date: 2020-09-21T12:32:20 request-id: 242cabdf-da4f-4633-8161-621b8a27d4a0 client-request-id: 242cabdf-da4f-4633-8161-621b8a27d4a0 ClientRequestId: 242cabdf-da4f-4633-8161-621b8a27d4a0

The code is below:

    string userName = ConfigurationManager.AppSettings["UserName"];
    string password = ConfigurationManager.AppSettings["Password"];

    System.Security.SecureString passWordSecureString = new System.Security.SecureString();

    foreach (char c in password.ToCharArray()) passWordSecureString.AppendChar(c);

    var clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    var tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

    string[] scopes = { "ChannelMessage.Send", "Group.ReadWrite.All", "User.Read" };

    IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
      .Create(clientId)
      .WithTenantId(tenantId)
      .Build();

    //creating the graph user context.
    UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

    GraphServiceClient graphServiceClient = new GraphServiceClient(authProvider);

    var user = await graphServiceClient.Me.Request()
                .WithUsernamePassword(userName, passWordSecureString)
                .GetAsync();

    var chatMessage = new ChatMessage
    {
        Body = new ItemBody
        {
            Content = "Hello world From Console App"
        },

        From = new IdentitySet()
        {
            User = new Identity()
            {
                Id = "{user_Id}",
                DisplayName = "FirstName LastName",

                AdditionalData = new Dictionary<string, object>()
                {
                  { "userIdentityType", "aadUser" }

                },
            }
        },
    };

    try
    {
        await graphServiceClient.Teams["{public_team_id}"].Channels["{channel_id}"].Messages
                                .Request()
                                .AddAsync(chatMessage);
    }
    catch (Exception exc)
    {
        Console.WriteLine("Error : " + exc.Message);
    }

Actually the user is not part of this particular public team so I think that is why it is giving this forbidden error. Can anybody please suggest the code to post the messages in a particular team channel wherein the user is not a member/owner of that team?

Upvotes: 0

Views: 879

Answers (1)

Hilton Giesenow
Hilton Giesenow

Reputation: 10854

If you want to post to a team you definitely need some kind of access rights to do so, but an incoming webhook is definitely your easiest solution.

Upvotes: 1

Related Questions