You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让控制台应用以服务用户身份认证调用Teams Graph API

实现无人值守的服务身份认证调用Graph API发送Teams消息

要实现无人工交互的服务身份认证,你需要使用客户端凭证流(Client Credential Flow),这是专为服务/后台应用设计的认证方式,无需用户参与。以下是具体实现步骤:

1. Azure AD应用配置前提

  • 确保你的Azure AD应用已注册完成,并且添加了Microsoft Graph的应用权限:
    • Chat.Create:用于创建Teams聊天
    • User.Read.All:用于通过user@odata.bind引用租户内用户
  • 对添加的应用权限完成管理员同意(应用权限必须由租户管理员授予)
  • 已生成并保存应用的客户端密钥(Client Secret),同时记录好ClientId、ClientSecret、TenantId

2. 修改代码实现服务身份认证

替换原代码中的DeviceCodeCredential相关逻辑,改用ClientSecretCredential实现无交互认证:

using Microsoft.Graph;
using Microsoft.Graph.Models;
using Azure.Identity;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

var clientId = Environment.GetEnvironmentVariable("ClientId");
var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
var tenantId = Environment.GetEnvironmentVariable("TenantId");

// 使用客户端凭证流初始化认证凭据
var clientSecretCredential = new ClientSecretCredential(
    tenantId,
    clientId,
    clientSecret,
    new ClientSecretCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    });

// 应用权限必须使用 /.default scope,获取所有已配置的应用权限令牌
var scopes = new[] { "https://graph.microsoft.com/.default" };

// 初始化Graph Service Client
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

// 创建一对一聊天的请求体
var requestBody = new Chat
{
    ChatType = ChatType.OneOnOne,
    Members = new List<ConversationMember>
    {
        new AadUserConversationMember
        {
            OdataType = "#microsoft.graph.aadUserConversationMember",
            Roles = new List<string> { "owner" },
            AdditionalData = new Dictionary<string, object>
            {
                { "user@odata.bind", "https://graph.microsoft.com/v1.0/users('svc_O365_user@mycompany.com')" }
            }
        },
        new AadUserConversationMember
        {
            OdataType = "#microsoft.graph.aadUserConversationMember",
            Roles = new List<string> { "owner" },
            AdditionalData = new Dictionary<string, object>
            {
                { "user@odata.bind", "https://graph.microsoft.com/v1.0/users('My.Name@mycompany.com')" }
            }
        }
    }
};

// 发送请求创建聊天
var result = await graphClient.Chats.PostAsync(requestBody);

关键说明

  • 客户端凭证流:ClientSecretCredential直接使用应用的ClientId和ClientSecret向Azure AD请求令牌,完全无需人工交互,适合后台/服务应用场景。
  • Scope注意事项:应用权限的请求必须使用https://graph.microsoft.com/.default作为scope,Azure AD会自动返回该应用已被授予的所有应用权限对应的令牌。
  • 权限验证:如果运行时出现权限不足的错误,检查Azure AD应用的权限是否已正确添加并完成管理员同意。

内容的提问来源于stack exchange,提问作者Michael LeVan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:54:52