【发布时间】:2018-09-05 22:58:35
【问题描述】:
在使用 Office365 Graph 获取 Teams 消息时遇到问题。
我使用
获取访问令牌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 端点运行正常。
我错过了什么,我假设它与访问令牌有关,但我所做的所有研究都没有解决这个问题。
【问题讨论】:
标签: c# api office365 microsoft-graph-api