当前位置: 首页 > 知识库问答 >
问题:

Azure Key Vault事件-可以订阅事件网格主题(不是系统事件网格主题)吗?

海岳
2023-03-14

我可以在Azure Key Vault中创建事件订阅,但它只允许系统事件网格主题,而不允许自定义事件网格主题。我的首选是自定义事件网格主题,因为我可以分配一个托管标识,并向该托管标识授予必要的RBAC。

是否可以将Azure Key Vault配置为将事件发送到自定义事件网格主题?

这是一个示例自定义事件网格主题:

{
    "name": "demoeventsubscription",
    "properties": {
        "topic": "/subscriptions/my-subscription-id/resourceGroups/EventGrids/providers/Microsoft.EventGrid/topics/kvTpoic",
        "destination": {
            "endpointType": "AzureFunction",
            "properties": {
                "resourceId": "/subscriptions/my-subscription-id/resourceGroups/aspnet4you/providers/Microsoft.Web/sites/afa-aspnet4you/functions/EventsProcessor",
                "maxEventsPerBatch": 1,
                "preferredBatchSizeInKilobytes": 64
            }
        },
        "filter": {
            "includedEventTypes": [
                "Microsoft.KeyVault.SecretNewVersionCreated"
            ],
            "advancedFilters": []
        },
        "labels": [],
        "eventDeliverySchema": "EventGridSchema"
    }
}

共有1个答案

居京
2023-03-14

@MayankBargali MSFT-感谢您在此处查看GitHub参考。您是对的,Azure资源(即密钥库、存储等)当前未设计为使用自定义事件网格主题。这些资源是为系统事件网格主题预先配置的,不允许客户附加标识,没有标识,客户无法保护目标或目标资源(事件订户)免受未授权访问。

作为客户,我的期望是,Azure要么允许自定义事件网格主题,要么修改系统事件网格主题附加托管身份的功能。我们将能够在目标资源上使用RBAC(在我的情况下是azure函数)来控制托管身份的安全性。

为了让大家知道,我使用了以下azure函数来验证系统事件网格主题在调用azure函数(webhook)时不会在请求头中传递任何标识-

using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AzureFunctionAppsCore
{
    public static class SampleEventGridConsumer
    {
        [FunctionName("SampleEventGridConsumer")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function begun");
            string response = string.Empty;
            

            try
            {
                JArray requestHeaders = Utils.GetIpFromRequestHeadersV2(req);
                log.LogInformation(requestHeaders.ToString());

                string requestContent = req.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                log.LogInformation($"Received events: {requestContent}");

                // Get the event type dynamically so that we can add/update custom event mappings to  EventGridSubscriber
                // Keep in mind, this is designed for Key Vault event type schema only.
                KeyVaultEvent[] dynamicEventsObject = JsonConvert.DeserializeObject<KeyVaultEvent[]>(requestContent);
                
                EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

                foreach(KeyVaultEvent kve in dynamicEventsObject)
                {
                    eventGridSubscriber.AddOrUpdateCustomEventMapping(kve.eventType, typeof(KeyVaultEventData));
                }
                
                EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);

                foreach (EventGridEvent eventGridEvent in eventGridEvents)
                {
                    if (eventGridEvent.Data is SubscriptionValidationEventData)
                    {
                        var eventData = (SubscriptionValidationEventData)eventGridEvent.Data;
                        log.LogInformation($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}");
                        // Do any additional validation (as required) such as validating that the Azure resource ID of the topic matches
                        // the expected topic and then return back the below response
                        var responseData = new SubscriptionValidationResponse()
                        {
                            ValidationResponse = eventData.ValidationCode
                        };



                        log.LogInformation($"Sending ValidationResponse: {responseData.ValidationResponse} and HttpStatusCode : {HttpStatusCode.OK}.");
                        
                        return new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent(JsonConvert.SerializeObject(responseData), Encoding.UTF8, "application/json")
                        };
                    }
                    else if (eventGridEvent.Data is StorageBlobCreatedEventData)
                    {
                        var eventData = (StorageBlobCreatedEventData)eventGridEvent.Data;
                        log.LogInformation($"Got BlobCreated event data, blob URI {eventData.Url}");
                    }
                    else if (eventGridEvent.Data is KeyVaultEventData)
                    {
                        var eventData = (KeyVaultEventData)eventGridEvent.Data;
                        log.LogInformation($"Got KeyVaultEvent event data, Subject is {eventGridEvent.Subject}");

                        var connectionString = Config.GetEnvironmentVariable("AzureWebJobsStorage");

                        // Retrieve storage account from connection string.
                        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

                        // Create the queue client.
                        CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

                        // Retrieve a reference to a container.
                        CloudQueue queue = queueClient.GetQueueReference("eventgridqueue");

                        // Create the queue if it doesn't already exist
                        await queue.CreateIfNotExistsAsync();

                        // Create a message and add it to the queue.
                        CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(eventGridEvent));
                        await queue.AddMessageAsync(message);

                    }
                }
            }
            catch(Exception ex)
            {
                log.LogError(ex.ToString());
            }


            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("Ok", Encoding.UTF8, "application/json")
            };
        }
    }

    public class KeyVaultEvent
    {
        public string id { get; set; }
        public string topic { get; set; }
        public string subject { get; set; }
        public string eventType { get; set; }
        public DateTime eventTime { get; set; }
        public KeyVaultEventData data { get; set; }
        public string dataVersion { get; set; }
        public string metadataVersion { get; set; }
    }

    public class KeyVaultEventData
    {
        public string Id { get; set; }
        public string vaultName { get; set; }
        public string objectType { get; set; }
        public string objectName { get; set; }
        public string version { get; set; }
        public string nbf { get; set; }
        public string exp { get; set; }
    }
}

助手功能:

public static JArray GetIpFromRequestHeadersV2(HttpRequestMessage request)
        {
            JArray values = new JArray();

            foreach(KeyValuePair<string, IEnumerable<string>> kvp in request.Headers)
            {
                values.Add(JObject.FromObject(new NameValuePair(kvp.Key, kvp.Value.FirstOrDefault())));
            }

            return values;
        }

共享我的项目依赖项。net core 3.1,如果您想在本地运行:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BouncyCastle.NetCore" Version="1.8.6" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.2.0" />
    <PackageReference Include="Microsoft.Azure.Management.Fluent" Version="1.34.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager.Fluent" Version="1.34.0" />
    <PackageReference Include="Microsoft.Azure.OperationalInsights" Version="0.10.0-preview" />
    <PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.5.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.EventGrid" Version="2.1.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.0" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.0" />
    <PackageReference Include="Microsoft.IdentityModel.Tokens.Saml" Version="5.6.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

那么,系统事件网格主题在调用azure函数时传递的标头是什么?

[{
        "name": "Accept-Encoding",
        "value": "gzip"
    }, {
        "name": "Connection",
        "value": "Keep-Alive"
    }, {
        "name": "Host",
        "value": "afa-aspnet4you.azurewebsites.net"
    }, {
        "name": "Max-Forwards",
        "value": "10"
    }, {
        "name": "aeg-subscription-name",
        "value": "MYSUBSCRIPTION2"
    }, {
        "name": "aeg-delivery-count",
        "value": "0"
    }, {
        "name": "aeg-data-version",
        "value": "1"
    }, {
        "name": "aeg-metadata-version",
        "value": "1"
    }, {
        "name": "aeg-event-type",
        "value": "Notification"
    }, {
        "name": "X-WAWS-Unencoded-URL",
        "value": "/api/SampleEventGridConsumer?code=removed=="
    }, {
        "name": "CLIENT-IP",
        "value": "52.154.68.16:58880"
    }, {
        "name": "X-ARR-LOG-ID",
        "value": "1e5b1918-9486-4b41-ab1d-7a644bc263d2"
    }, {
        "name": "DISGUISED-HOST",
        "value": "afa-aspnet4you.azurewebsites.net"
    }, {
        "name": "X-SITE-DEPLOYMENT-ID",
        "value": "afa-aspnet4you"
    }, {
        "name": "WAS-DEFAULT-HOSTNAME",
        "value": "afa-aspnet4you.azurewebsites.net"
    }, {
        "name": "X-Original-URL",
        "value": "/api/SampleEventGridConsumer?code=removed=="
    }, {
        "name": "X-Forwarded-For",
        "value": "52.154.68.16:58880"
    }, {
        "name": "X-ARR-SSL",
        "value": "2048|256|C=US, O=Microsoft Corporation, CN=Microsoft RSA TLS CA 01|CN=*.azurewebsites.net"
    }, {
        "name": "X-Forwarded-Proto",
        "value": "https"
    }, {
        "name": "X-AppService-Proto",
        "value": "https"
    }, {
        "name": "X-Forwarded-TlsVersion",
        "value": "1.2"
    }
]

Azure函数使用api密钥,但它是共享的,在生产系统中不被视为真正的安全性。系统主题未发送任何可用于查找任何标识的标头。

此处显示的Azure函数处理的几个事件-

[{
        "id": "2ff9617d-e498-4527-8467-d36eeff6b94b",
        "topic": "/subscriptions/truncated/resourceGroups/key-vaults/providers/Microsoft.KeyVault/vaults/aspnet4you-keyvault",
        "subject": "TexasSnow",
        "eventType": "Microsoft.KeyVault.SecretNewVersionCreated",
        "data": {
            "Id": "https://aspnet4you-keyvault.vault.azure.net/secrets/TexasSnow/106b1d8450e6404bb323abf650c81496",
            "VaultName": "aspnet4you-keyvault",
            "ObjectType": "Secret",
            "ObjectName": "TexasSnow",
            "Version": "106b1d8450e6404bb323abf650c81496",
            "NBF": null,
            "EXP": null
        },
        "dataVersion": "1",
        "metadataVersion": "1",
        "eventTime": "2021-02-20T06:50:08.6207125Z"
    }
]

[
    {
        "id": "996c900f-b697-4754-916c-67e485e141f9",
        "topic": "/subscriptions/b63613a2-9fc8-47ad-a65c-e1d1eba108be/resourceGroups/key-vaults/providers/Microsoft.KeyVault/vaults/aspnet4you-keyvault",
        "subject": "EventTestKey",
        "eventType": "Microsoft.KeyVault.KeyNewVersionCreated",
        "data": {
            "Id": "https://aspnet4you-keyvault.vault.azure.net/keys/EventTestKey/22f3358955174cff9f5d5f24f5f2ecb0",
            "VaultName": "aspnet4you-keyvault",
            "ObjectType": "Key",
            "ObjectName": "EventTestKey",
            "Version": "22f3358955174cff9f5d5f24f5f2ecb0",
            "NBF": null,
            "EXP": null
        },
        "dataVersion": "1",
        "metadataVersion": "1",
        "eventTime": "2021-02-20T20:08:00.4520828Z"
    }
]

那么,下一步是什么?正如@MayankBargali MSFT所说,azure正在按设计工作。我已向feedback.azure.com发送了功能请求。

 类似资料:
  • 基本上,我试图使用ARM部署一个事件网格订阅来收集订阅中的特定事件(主题类型= Azure订阅)。我已经有一个创建了事件网格触发功能的功能应用程序,只需要将该功能与事件网格订阅绑定为webhook。 我正在使用Azure DevOps中的发布管道来自动化整个工作流。 以下是我使用的一个示例: 这最终部署了事件网格主题,而不是事件网格订阅。 然后,有人建议我尝试以下操作: 但是这最终以这个错误而失败

  • 我正试图开发一个Azure函数来处理由事件中心的捕获功能创建的blob。然而,尽管捕获blobs被正确地存储在容器中,但似乎没有< code>Microsoft。EventHub . capturefile created 事件发布到函数订阅。功能endpoint的事件订阅已创建,没有错误,Azure CLI的输出为 该函数的主体是一个标准的Http触发器,其中包含事件网格endpoint订阅所需

  • 我正在尝试过滤事件网格中的事件,使其仅在我的订阅中的Azure功能更改时触发(例如配置更改、代码更新或创建/删除新功能)。 我使用的 PowerShell 脚本如下所示: 这将过滤到所有功能和网站(请检查<code>和$AdvancedFilters)。是否有任何方法可以将事件仅过滤到Azure函数?欢迎使用Azure CLI、portal、Powershell或.net sdk中的任何解决方案帮

  • Node.js应用程序可以使用composer-client.BusinessNetworkConnection.onAPI调用从业务网络订阅事件。事件在业务网络模型文件中定义,并由交易处理函数文件中的指定交易处理。有关发布事件的更多信息,请参阅发布事件。 在你开始之前 在应用程序可以订阅事件之前,你必须定义一些事件和发送它们的交易。还必须部署业务网络,并且必须具有可连接到该业务网络的连接配置文件

  • 我正在使用服务总线溢价来创建事件订阅(事件网格)和我正在使用Webook(逻辑应用endpoint)的endpoint。 我的用例是:无论何时在服务总线主题中收到消息,事件都应该触发,并且应该调用webhook。 webhookendpoint是逻辑应用程序URI。 问题:对于主题中的15-20条消息,事件将被触发,逻辑应用程序将被触发,之后,即使对于任意数量的消息,事件也不会被触发。 注意:我在

  • 我无法在Azure事件网格中添加新的WebHook订阅。有人能帮忙吗?当我添加webhookendpoint时,出现以下错误。