如何在Audit.NET审计追踪实现中使用用户分配托管标识连接Azure表存储
使用用户分配托管标识连接Azure表存储(Audit.NET + .NET 8 Web API)
完全可以使用用户分配托管标识连接Azure表存储,替代连接字符串的方式。以下是实现步骤和代码示例:
前提准备
- 在Azure门户中为你的Web API应用配置用户分配托管标识。
- 给该托管标识分配Azure表存储的Storage Table Data Contributor(或对应所需的权限)角色,确保它具备读写审计表的权限。
- 安装
Azure.IdentityNuGet包(用于托管标识认证逻辑)。
修改Audit.NET配置代码
将原有的连接字符串配置,替换为通过用户分配托管标识认证的方式:
using Azure.Identity; using Azure.Data.Tables; public void AuditSetupOutput(IApplicationBuilder app) { var options = new JsonSerializerOptions() { WriteIndented = true }; // 替换为你的用户分配托管标识客户端ID var userAssignedClientId = "你的托管标识客户端ID"; // 替换为你的Azure存储账户服务URI var storageServiceUri = new Uri("https://<你的存储账户名>.table.core.windows.net"); Configuration.Setup() .JsonSystemAdapter(options) .UseAzureTableStorage(config => config // 使用ClientFactory创建带托管标识认证的TableClient,替代连接字符串 .ClientFactory(tableName => { var credential = new UserAssignedManagedIdentityCredential(userAssignedClientId); var tableClient = new TableClient(storageServiceUri, tableName, credential, new TableClientOptions() { Retry = { MaxRetries = 3 } }); // 可选:确保目标表存在,根据业务需求调整 tableClient.CreateIfNotExists(); return tableClient; }) .TableName(evt => $"{_TargetTableName}{DateTime.UtcNow:MMMyyyy}") .EntityBuilder(builder => builder .PartitionKey(auditEvent => auditEvent.EventType) .RowKey(auditEvent => Guid.NewGuid().ToString("N")) .Columns(col => col .FromDictionary(auditEvent => new Dictionary<string, object>() { { "EventType", auditEvent.EventType }, { "UserName", auditEvent.Environment.UserName }, { "EventDuration", auditEvent.Duration }, { "DataSize", auditEvent.ToJson().Length }, { "Data", auditEvent.ToJson().Length >= 32000 ? CompressAuditEventData(auditEvent.ToJson()): auditEvent.ToJson()} }))))); // 保留原有TraceId的自定义配置 var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>(); Configuration.AddCustomAction(ActionType.OnScopeCreated, scope => { scope.SetCustomField("TraceId", httpContextAccessor.HttpContext?.TraceIdentifier); }); }
关键说明
UserAssignedManagedIdentityCredential:明确指定使用用户分配的托管标识进行认证,只需传入托管标识的客户端ID。TableClient构建:通过存储账户的服务URI、托管标识凭证创建客户端,完全替代了连接字符串的认证逻辑。- 原有业务逻辑:保留了你之前配置的表命名规则、审计实体字段构建以及TraceId追踪逻辑,无需额外修改。
内容的提问来源于stack exchange,提问作者santosh kumar patro
相关产品推荐
相关产品推荐

