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

Validation not strictly required for Event Grid subscriptions?

Azure 事件网格的 documentation

Your app needs to respond by echoing back the validation code. Event Grid does not deliver events to WebHook endpoints that have not passed the validation.

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

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

令牌交换发生在 Azure Functions 的幕后,因此您不需要回显验证码。这同样适用于逻辑应用程序。

如果您使用基于 "Event Grid Trigger" 的 Azure 函数作为您的事件订阅目标,订阅验证将自动处理。从 2018-01-01 API 版本开始,如果您使用基于 "HTTP trigger" 的函数(作为事件订阅创建期间的目标端点),您将需要在代码中处理此验证。这记录在 https://docs.microsoft.com/en-us/azure/event-grid/overview.

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

第 1 步:添加对 Microsoft.Azure.EventGrid 的依赖: 为此,请单击 Azure 函数中的 "View Files" link(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);    
}