事件网格订阅不是严格要求的验证?

时间:2017-10-05 07:41:53

标签: azure azure-eventgrid

Azure Event Grid的documentation

  

您的应用需要通过回显验证码来做出响应。 Event Grid不会将事件传递给尚未通过验证的WebHook端点。

我创建了我的WebHook Azure功能,它可以提供任何POST请求,而无需验证代码。尽管如此,我仍然看到我发送的自定义事件来到此端点。

为什么在这种情况下严格要求验证?

2 个答案:

答案 0 :(得分:1)

令牌交换发生在Azure Functions的幕后,因此您无需回显验证代码。这同样适用于Logic Apps。

答案 1 :(得分:1)

如果您使用基于Azure功能的“事件网格触发器”作为事件订阅目标,则会自动处理订阅验证。从2018-01-01 API版本开始,如果您使用的是基于“HTTP触发器”的函数(在创建事件订阅期间作为目标端点),则需要在代码中处理此验证。这在https://docs.microsoft.com/en-us/azure/event-grid/overview记录。

以下是C#中的一些示例代码:

步骤1:向Microsoft.Azure.EventGrid添加依赖项: 为此,请单击Azure功能中的“查看文件”链接(Azure功能门户中最右侧的窗格),然后创建名为project.json的文件。将以下内容添加到project.json文件并保存:

{
    "frameworks": {
        "net46": {
            "dependencies": {
               "Microsoft.Azure.EventGrid": "1.1.0-preview"
             }
         }
     }
}

步骤2:处理订阅验证事件:

using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Microsoft.Azure.EventGrid.Models;

class SubscriptionValidationEventData
{
    public string ValidationCode { get; set; }
}

class SubscriptionValidationResponseData
{
    public string ValidationResponse { get; set; }
}

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,  TraceWriter log)
{
    string response = string.Empty;
    const string SubscriptionValidationEvent  = "Microsoft.EventGrid.SubscriptionValidationEvent";

    string requestContent = await req.Content.ReadAsStringAsync();
    EventGridEvent[] eventGridEvents = JsonConvert.DeserializeObject<EventGridEvent[]>(requestContent);

    foreach (EventGridEvent eventGridEvent in eventGridEvents)
    {
        JObject dataObject = eventGridEvent.Data as JObject;

        // Deserialize the event data into the appropriate type based on event type
        if (string.Equals(eventGridEvent.EventType, SubscriptionValidationEvent, StringComparison.OrdinalIgnoreCase))
        {
            var eventData = dataObject.ToObject<SubscriptionValidationEventData>();
            log.Info($"Got SubscriptionValidation event data, validation code {eventData.ValidationCode}, topic={eventGridEvent.Topic}");
            // Do any additional validation (as required) and then return back the below response
            var responseData = new SubscriptionValidationResponseData();
            responseData.ValidationResponse = eventData.ValidationCode;
            return req.CreateResponse(HttpStatusCode.OK, responseData);   
        }            
    }

    return req.CreateResponse(HttpStatusCode.OK, response);    
}