Код: Выделить всё
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace AzureKeyVaultIntegration
{
public class AzureKeyVaultHelper
{
// Replace with your Azure AD Tenant ID, Client ID, and Client Secret
private const string TenantId = "TenantId";
private const string ClientId = "ClientId";
private const string ClientSecret = "ClientSecret";
private const string KeyVaultBaseUrl = "https://testakv123.vault.azure.net/";// Replace with your Key Vault name
private static readonly HttpClient httpClient = new HttpClient();
private readonly string _keyVaultUri1;
public AzureKeyVaultHelper(string keyVaultUri)
{
_keyVaultUri1 = keyVaultUri;
}
// Get OAuth2 access token from Azure AD using client credentials
public static async Task GetAccessTokenAsync()
{
var tokenUrl = $"https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/token";
var requestData = new Dictionary
{
{"grant_type", "client_credentials"},
{"client_id", ClientId},
{"client_secret", ClientSecret},
{"scope", "https://vault.azure.net/.default"}
};
var requestContent = new FormUrlEncodedContent(requestData);
var response = await httpClient.PostAsync(tokenUrl, requestContent);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
dynamic json = JsonConvert.DeserializeObject(jsonResponse);
return json.access_token;
}
// Fetch secret from Azure Key Vault
public static async Task GetSecretAsync(string secretName)
{
string accessToken = await GetAccessTokenAsync();
var requestUrl = $"{KeyVaultBaseUrl}/secrets/{secretName}?api-version=7.2";
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Add("Authorization", $"Bearer {accessToken}");
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
dynamic json = JsonConvert.DeserializeObject(jsonResponse);
return json.value;
}
}
}
Код: Выделить всё
//using Azure.Identity;
//using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.DependencyInjection;
//using WebAppWithKeyVault;
using KeyVaultHelper;
using AzureKeyVaultIntegration;
var builder = WebApplication.CreateBuilder(args);
// Set up the Key Vault URI (either hard-coded or from app settings)
string keyVaultUri = builder.Configuration["KeyVaultUri"] ??
"https://testakv123.vault.azure.net/";
// Register the KeyVaultService as a singleton
builder.Services.AddSingleton(new KeyVaultService(keyVaultUri));
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
Код: Выделить всё
using Microsoft.AspNetCore.Mvc.RazorPages;
using KeyVaultHelper;
using AzureKeyVaultIntegration;
public class IndexModel : PageModel
{
//private readonly KeyVaultService _keyVaultService;
private readonly AzureKeyVaultHelper _keyVaultService1;
public string SecretValue { get; private set; }
/* public IndexModel(KeyVaultService keyVaultService)
{
_keyVaultService = keyVaultService;
}*/
public IndexModel(AzureKeyVaultHelper AzureKeyVaultHelper)
{
_keyVaultService1 = AzureKeyVaultHelper;
}
public void OnGet()
{
// Use the KeyVaultService to fetch the secret
// SecretValue = _keyVaultService.GetSecret("Test3"); //Using AKV out of the
box lib
SecretValue = AzureKeyVaultHelper.GetSecretAsync("Test3").ToString();
//Using REST API
//SecretValue = await AzureKeyVaultHelper.GetSecretAsync("Test3");
}
}
Код: Выделить всё
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
Welcome
Learn about [url=https://learn.microsoft.com/aspnet/core]building Web
apps
with ASP.NET Core[/url].
Код: Выделить всё
The secret value is: @Model.SecretValue
Код: Выделить всё
Now listening on: https://localhost:7266
Сейчас слушаю: http://localhost:5009
информация: Microsoft.Hosting.Lifetime[0]
Приложение запущено. Нажмите Ctrl+C, чтобы завершить работу.
информация: Microsoft.Hosting.Lifetime[0]
Среда хостинга: Разработка
информация: Microsoft.Hosting.Lifetime[0]
Корень содержимого путь: C:\Users\routj\source\repos\WebApplication1
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
Во время выполнения запроса произошло необработанное исключение.
System. InvalidOperationException: невозможно разрешить службу для типа «AzureKeyVaultIntegration.AzureKeyVaultHelper» при попытке активировать «IndexModel».
в Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type type, Type requireBy)
atlambda_method5(Closure) , IServiceProvider, Object[])
в Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.c__DisplayClass3_0.b__0(PageContext pageContext)
в Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker. CreateInstance()
в Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope&scope, Object&state, Boolean& isCompleted)
в Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker .InvokeInnerFilterAsync()
в Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(вызов ResourceInvoker, Task LastTask, Состояние следующее, Область области, Состояние объекта, Логическое значение isCompleted)
в Microsoft.AspNetCore. Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
в Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope&scope, Object&state, Boolean& isCompleted)
в Microsoft.AspNetCore.Mvc .Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- Конец трассировки стека из предыдущего местоположения ---
в Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(вызов ResourceInvoker, Task Task, Область IDisposable)
в Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(вызов ResourceInvoker, задача Task, область IDisposable)
в Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)< /p>
Почему возникает эта ошибка? Любая помощь будет оценена по достоинству. Спасибо
Подробнее здесь: https://stackoverflow.com/questions/791 ... aulthelper
Мобильная версия