You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python验证Azure Event Grid订阅失败,遇405错误求助

Azure Event Grid Webhook验证失败,返回405 Method Not Allowed

问题描述

在完成Azure Event Grid事件的Webhook验证时,收到如下错误:

POST / HTTP/1.1 405 (Method Not Allowed)

事件订阅部署失败,错误信息:

{"code":"URL validation", "message":"Webhook验证握手在https://XXXXX.ngrok.app/失败。HTTP POST请求返回未知响应码。"}

已参考官方指导但未定位到原因,以下是我的实现代码:

Webhook路由代码

# Define the webhook route    
webhook_blueprint = Blueprint('webhook', __name__)

# Define the webhook route
@webhook_blueprint.route('/webhook', methods=['POST'])
def handle_webhook():
    from pprint import pprint
    try:
        # Get headers and data
        headers = request.headers
        data = request.get_json()
        
        # Log incoming request
        pprint(f"Incoming webhook headers: {headers}")
        pprint(f"Incoming webhook data: {data}")

        # Check if this is a validation request
        if headers.get('aeg-event-type') == 'SubscriptionValidation':
            pprint("Received subscription validation request")
            
            # Process the validation event
            for event in data:
                if event['eventType'] == 'Microsoft.EventGrid.SubscriptionValidationEvent':
                    validation_code = event['data']['validationCode']
                    pprint(f"Returning validation code: {validation_code}")
                    
                    # Return the validation response
                    return jsonify({
                        "validationResponse": validation_code
                    })

        # Handle your original webhook logic for non-validation requests
        pprint("Processing regular webhook request")

        
        #TODO: Write Webhook routing
        pprint(f"Processing webhook data: {data}")
        
        return jsonify({'status': 'success'}), 200

CORS配置代码

# Configure CORS specifically for the webhook blueprint
CORS(webhook_blueprint, 
     origins="*",
    methods=['POST'],
    supports_credentials=False)

解决方案

1. 修复请求路径不匹配问题

错误日志显示Azure向根路径/发送POST请求,但你的代码中Webhook路由绑定的是/webhook,根路径未配置POST方法处理逻辑,因此返回405错误。

解决方法:
修改Azure Event Grid事件订阅的Webhook端点为https://XXXXX.ngrok.app/webhook,确保与代码中的路由路径完全一致。

2. 更新CORS配置以支持预请求

Azure Webhook验证可能会发送OPTIONS预请求,当前CORS配置仅允许POST方法,会导致预请求失败。更新配置添加OPTIONS方法:

# Configure CORS specifically for the webhook blueprint
CORS(webhook_blueprint, 
     origins="*",
     methods=['GET', 'POST', 'OPTIONS'],  # 新增OPTIONS和GET以兼容不同验证模式
     supports_credentials=False)

3. 兼容两种验证模式(可选)

Azure Event Grid支持POST验证(推荐)和GET验证两种模式,若需兼容GET验证,可修改路由允许GET方法并添加对应处理逻辑:

@webhook_blueprint.route('/webhook', methods=['GET', 'POST'])
def handle_webhook():
    from pprint import pprint
    try:
        # 处理GET验证请求
        if request.method == 'GET':
            validation_code = request.args.get('validationCode')
            if validation_code:
                pprint(f"Returning GET validation code: {validation_code}")
                return jsonify({
                    "validationResponse": validation_code
                })
        
        # 原POST请求处理逻辑
        headers = request.headers
        data = request.get_json()
        
        pprint(f"Incoming webhook headers: {headers}")
        pprint(f"Incoming webhook data: {data}")

        if headers.get('aeg-event-type') == 'SubscriptionValidation':
            pprint("Received subscription validation request")
            
            for event in data:
                if event['eventType'] == 'Microsoft.EventGrid.SubscriptionValidationEvent':
                    validation_code = event['data']['validationCode']
                    pprint(f"Returning validation code: {validation_code}")
                    
                    return jsonify({
                        "validationResponse": validation_code
                    })

        pprint("Processing regular webhook request")
        pprint(f"Processing webhook data: {data}")
        
        return jsonify({'status': 'success'}), 200

验证步骤

  1. 确认事件订阅的端点路径已更新为/webhook
  2. 重启Flask服务
  3. 重新触发事件订阅验证,查看日志确认请求到达/webhook路由并正确返回响应

内容的提问来源于stack exchange,提问作者Kakobo kakobo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 14:05:58