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

时间:2017-03-27 03:38:01

标签: azure azure-active-directory webhooks microsoft-graph azure-ad-graph-api

我要做的是使用Microsoft在this article中描述的“代表流的Web API”方案来创建Web挂钩。

所以我从Microsoft github example开始,并确保我可以通过图谱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);
}

我从回复中得到的错误是:

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

webhook创建代码直接来自ASP.NET webhook github sample project,我也确保我可以成功运行。

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

// 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);

所以我想找出:

  1. 是否使用甚至支持的代表流通过图API创建webhook?不确定this SO question是否是我在这里寻找的。
  2. 如果支持,我在这里缺少什么?
  3. 如果不支持,是否有其他方法可以实现?例如。我可以使用现有的Office 365 API吗?

1 个答案:

答案 0 :(得分:6)

  
    

&#34; message&#34;:&#34;访问令牌验证失败。&#34;,

  

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