使用"代表流的Web API"创建Microsoft Graph webhook时访问令牌验证失败

Leo*_*hou 1 azure webhooks azure-active-directory azure-ad-graph-api microsoft-graph

我想要做的是使用Microsoft 本文中描述的"Web API代表流"方案来创建Web挂钩.

所以我从Microsoft github示例开始,确保我可以通过Graph API成功获取用户配置文件.

然后我修改了获取用户配置文件的代码来创建Web挂钩,因此代码如下所示:

// Authentication and get the access token on behalf of a WPF desktop app.
// This part is unmodified from the sample project except for readability.

const string authority = "https://login.microsoftonline.com/mycompany.com";
const string resource = "https://graph.windows.net";
const string clientId = "my_client_id";
const string clientSecret = "my_client_secret";
const string assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer";

var user = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var authenticationContext = new AuthenticationContext(authority,new DbTokenCache(user));
var assertion = ((BootstrapContext) ClaimsPrincipal.Current.Identities.First().BootstrapContext).Token;
var userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null
    ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value
    : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;

var result = await authenticationContext.AcquireTokenAsync(resource,new ClientCredential(clientId,clientSecret),new UserAssertion(assertion,assertionType,userName));

var accessToken = result.AccessToken;


// After getting the access token on behalf of the desktop WPF app,
// subscribes to get notifications when the user receives an email.
// This is the part that I put in.

var subscription = new Subscription
{
    Resource = "me/mailFolders('Inbox')/messages",
    ChangeType = "created",
    NotificationUrl = "https://mycompany.com/subscription/listen",
    ClientState = Guid.NewGuid().ToString(),
    ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 4230, 0)
};

const string subscriptionsEndpoint = "https://graph.microsoft.com/v1.0/subscriptions/";
var request = new HttpRequestMessage(HttpMethod.Post, subscriptionsEndpoint);

var contentString = JsonConvert.SerializeObject(subscription, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
request.Content = new StringContent(contentString, System.Text.Encoding.UTF8, "application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = await new HttpClient().SendAsync(request);

if (response.IsSuccessStatusCode)
{
    // Parse the JSON response.
    var stringResult = await response.Content.ReadAsStringAsync();
    subscription = JsonConvert.DeserializeObject<Subscription>(stringResult);
}
Run Code Online (Sandbox Code Playgroud)

我从响应中得到的错误是:

{
 "error":
 {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError":
    {
      "request-id": "f64537e7-6663-49e1-8256-6e054b5a3fc2",
      "date": "2017-03-27T02:36:04"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

webhook创建代码直接来自ASP.NET webhook github示例项目,我也确保我可以成功运行.

相同的访问令牌代码与原始用户配置文件读取代码一起使用:

// Call the Graph API and retrieve the user's profile.

const string requestUrl = "https://graph.windows.net/mycompany.com/me?api-version=2013-11-08";
request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await new HttpClient().SendAsync(request);
Run Code Online (Sandbox Code Playgroud)

所以我想找出:

  1. 是否使用甚至支持的代表流通过图形API创建webhook?不确定这个问题是否是我在这里寻找的.
  2. 如果支持,我在这里缺少什么?
  3. 如果它不受支持,是否有替代方案可以实现它?例如,我可以使用现有的Office 365 API吗?

Nan*_* Yu 6

"message":"访问令牌验证失败.",

该错误意味着您获得了资源的错误访问令牌.根据您的代码,您获取资源的访问令牌:https://graph.windows.net(Azure AD Graph API),但随后您使用该访问令牌访问Microsoft Graph API(https://graph.microsoft. com),因此访问令牌验证失败.