Office 365 图形获取Microsoft团队消息



在使用 Office365 图形获取团队消息时遇到问题。

我使用

string signedInUserID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
if (HttpContext.Current.Application.Count > 0)
{
signedInUserID = HttpContext.Current.Application.Keys[0].Replace("_TokenCache", "");
}
HttpContextBase httpContextBase = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;
ADALTokenCache tokenCache = new ADALTokenCache(signedInUserID);
var cachedItems = tokenCache.ReadItems(); // see what's in the cache
AuthenticationContext authContext = new AuthenticationContext(Authority, tokenCache);
ClientCredential clientCredential = new ClientCredential(clientId, appKey);
string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
UserIdentifier userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
try
{
AuthenticationResult result = await authContext.AcquireTokenAsync(graphResourceID2, clientCredential).ConfigureAwait(false);
return result.AccessToken;
}

然后,要获取 Teams 消息,我将其用作 endoint:

https://graph.microsoft.com/beta/teams/{teamID}/channels/{channelid}/messages

使用从上面接收的访问令牌和端点,我执行以下操作:

using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var result = JsonConvert.DeserializeObject<GraphOdataResponse>(json);
myTeamsMessages = result.messages.ToList();
}
return myTeamsMessages;
}
}
}

每次它针对任何 beta 终结点运行时,都会引发未经授权的错误,但针对 v1.0 终结点,它工作正常。

我错过了什么,我假设它与访问令牌有关,但我所做的所有研究都没有解决这个问题。

Beta 版本仍可能发生变化,因此如果可能,请使用 V1.0 端点。对于未经授权的错误,我无法完全重现该问题。根据我的测试,该终结点在图形资源管理器中运行良好:

https://graph.microsoft.com/beta(V1.0)/teams/{teamID}/channels/{channelid}/messages

但是根据我的测试,端点在 MVC/NETCore 项目中不起作用,我使用了以下身份验证令牌,但没有您使用的 ADALToken:

string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync(); 

我的总结异常是由令牌逻辑引起的,而不是由 HttpClient 请求引起的,我可以使用该请求来处理其他 api。还有一种可能,我们无法确认,就是 API 内部处理遇到了问题。但是我们可以在 Graph 资源管理器中使用 API,所以这种可能性也不高。我认为您可以先尝试其他令牌,但不能尝试 ADALToken。

最新更新