首页 > 解决方案 > 如何使用 MSgraph 处理 webhook 验证请求?

问题描述

我正在尝试在 Microsoft azure 中注册我的 Web 应用程序,以获取有关用户单驱更改的通知。为此,我需要注册我的应用以获取通知。

我一直在遵循这些说明:创建订阅

和这里处理 webhook 验证请求

但我需要一些帮助来验证 webhook。创建新订阅时,OneDrive 将以以下格式向注册的 URL(我的 Web 应用程序或者我可能会使用 azure 函数)发布请求:

POST https://contoso.azurewebsites.net/your/webhook/service?validationtoken={randomString}

Content-Length: 0

为了成功创建订阅,我的服务必须通过将validationtoken 查询字符串参数的值作为纯文本响应返回来响应此请求。

HTTP/1.1 200 OK
Content-Type: text/plain

{randomString}

我正在使用 django ,如何像他们问的那样在 python 中做出响应?

这就是我发送第一个帖子请求的方式

def create_subscription(token):
  payload = {
    "changeType": "updated",
    "notificationUrl": notification_url,
    "resource": "/me/drive/root",
    "expirationDateTime": "2030-01-01T11:23:00.000Z",
    "clientState": "client-specific string"
  }

  headers = {
    "Authorization": token['access_token'],
    "Host": "graph.microsoft.com",
    "Content-Type": "application/json"
  }

  response = requests.post("https://graph.microsoft.com/v1.0/subscriptions".format(graph_url),
                           data=json.dumps(payload), headers=headers)

这就是我对 Microsoft 的 POST 请求做出响应的方式

def validate_subscription(request):

    if request.method == 'POST':
      url = request.get_full_path()
      parsed = urlparse.urlparse(url)
      validation_string = parsed.query['validationtoken']

      headers = {
        "Host": "graph.microsoft.com",
        "Content-Type": "text/plain"
      }
      r = requests.post("{0}/subscriptions".format(graph_url),
                           data=validation_string, headers=headers)
      if (r.status_code == 200):
        return HttpResponse("Subscription suceeded")

我们不断收到错误提示“验证错误”

感谢你们

标签: pythondjangoazuremicrosoft-graph-api

解决方案


您不应该向 Graph 发送请求,而应该使用传入的令牌POST响应Graph 的请求:

  1. 您创建订阅
  2. GraphPOST使用验证令牌向您的通知端点发出一个。
  3. 您的通知端点通过以下方式响应POST

    def validate_subscription(request):
        if request.method == 'POST':
            url = request.get_full_path()
            parsed = urlparse.urlparse(url)
            validation_string = parsed.query['validationtoken']
            return HttpResponse(validation_string, content_type="text/plain")
    

推荐阅读