Visual Studio 2013下C#发送Teams私信的无Azure.Identity认证方案
在Visual Studio 2013的C#项目中发送Teams私信的解决方案(无需Azure.Identity)
完全可以实现,由于Visual Studio 2013仅支持.NET Framework 4.5/4.6.x(不兼容.NETStandard 2.0),我们可以通过手动实现客户端凭据流获取令牌+使用旧版本Microsoft Graph SDK的方式绕过Azure.Identity的依赖限制,具体步骤如下:
1. 准备Azure AD应用配置
先在Azure AD中注册后台服务类型的应用,完成以下配置:
- 记录应用的租户ID、客户端ID、客户端密钥;
- 为应用添加Microsoft Graph的应用权限:
Chat.Create和ChatMessage.Send,并让管理员完成权限同意。
2. 手动实现令牌获取逻辑
不需要依赖任何身份验证SDK,直接用HttpClient向Azure AD令牌端点发送请求获取访问令牌:
using System; using System.Net.Http; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; // 可通过NuGet安装Newtonsoft.Json,VS2013支持 public static async Task<string> GetGraphAccessToken(string tenantId, string clientId, string clientSecret) { var tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/token"; var requestParams = new Dictionary<string, string> { { "grant_type", "client_credentials" }, { "client_id", clientId }, { "client_secret", clientSecret }, { "resource", "https://graph.microsoft.com" } }; using (var httpClient = new HttpClient()) { var response = await httpClient.PostAsync(tokenEndpoint, new FormUrlEncodedContent(requestParams)); response.EnsureSuccessStatusCode(); var responseJson = await response.Content.ReadAsStringAsync(); var tokenResult = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson); return tokenResult["access_token"].ToString(); } }
3. 集成旧版本Microsoft Graph SDK
安装Microsoft.Graph的1.x版本(例如1.28.0,该版本支持.NET Framework 4.5),然后实现自定义认证提供器:
using Microsoft.Graph; using System.Net.Http; using System.Threading.Tasks; public class GraphAuthProvider : IAuthenticationProvider { private readonly Func<Task<string>> _tokenGetter; public GraphAuthProvider(Func<Task<string>> tokenGetter) { _tokenGetter = tokenGetter; } public async Task AuthenticateRequestAsync(HttpRequestMessage request) { var accessToken = await _tokenGetter(); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); } }
4. 发送Teams私信示例
初始化Graph客户端后,即可创建一对一聊天并发送消息:
// 替换为你的配置参数 var tenantId = "你的租户ID"; var clientId = "你的客户端ID"; var clientSecret = "你的客户端密钥"; var targetUserId = "目标用户的Azure AD ID"; // 初始化认证提供器和Graph客户端 var authProvider = new GraphAuthProvider(() => GetGraphAccessToken(tenantId, clientId, clientSecret)); var graphClient = new GraphServiceClient(authProvider); // 创建一对一聊天 var newChat = new Chat { ChatType = ChatType.OneOnOne, Members = new List<ConversationMember> { new AadUserConversationMember { Roles = new List<string> { "owner" }, UserId = targetUserId } } }; var createdChat = await graphClient.Chats.Request().AddAsync(newChat); // 发送消息 var message = new ChatMessage { Body = new ItemBody { ContentType = BodyType.Text, Content = "这是通过VS2013项目发送的Teams私信" } }; await graphClient.Chats[createdChat.Id].Messages.Request().AddAsync(message);
关键注意事项
- 必须使用
Microsoft.Graph1.x版本,最新版依赖.NETStandard 2.0无法在VS2013中使用; - 应用权限必须是应用权限而非委托权限,且必须经过管理员同意;
- 可以添加令牌缓存逻辑,避免重复请求令牌(比如根据返回的
expires_on字段缓存令牌)。
内容的提问来源于stack exchange,提问作者Johnny
相关产品推荐
相关产品推荐

