gpt4 book ai didi

c# - 尝试从 Asp.net core 中的 Azure Key Vault 访问对象值

转载 作者:行者123 更新时间:2023-12-02 06:19:07 25 4
gpt4 key购买 nike

我在 azure 的 key 保管库 key 中有一个对象值,并尝试在启动类中读取该值,但该值始终为 null。

程序.cs

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));

config.AddAzureKeyVault(
vaultConfig.AzureVaultUrl,
keyVaultClient,
new DefaultKeyVaultSecretManager());

Startup.cs

public virtual void ConfigureSettings(IServiceCollection services)
{
services.AddOptions();
services.Configure<OktaConfig>(Configuration.GetSection("OktaConfig")); // Read the value from Azure Key Vault or %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json for Dev Environment
}

Controller .cs

 public class SystemController
{

private readonly IConfiguration _config;
private readonly OktaConfig _oktaConfig;

public SystemController(IConfiguration config, IOptions<OktaConfig> oktaConfig)
{
_config = config;
_oktaConfig = oktaConfig.Value; // This value is null
}


[HttpGet("Vaults")]
public IActionResult GetVaultValues()
{
var OktaConfig = JsonConvert.DeserializeObject<OktaConfig>(_config["OktaConfig"]);
return Ok(OktaConfig);
}

_oktaConfig 值始终为空。

这是我的 Azure Key Vault 值

enter image description here

key secret 值的Json结构

{
"OktaDomain": "https://dev-166545.okta.com/oauth2/XXXXXXXXXXXXXXXXX/v1/authorize",
"ClientId": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
"ClientSecret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"redirectUrl": "https://localhost:44307"
}

ViewModel.cs

public class OktaConfig
{
public string RedirectUrl { get; set; }
public string OktaDomain { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string ClientName { get; set; }
}

通过这个 _config["OktaConfig"] 代码,我可以获得该值,但我想为此进行依赖项注入(inject)。

最佳答案

我在我这边做了一个快速测试,这是我的用于快速测试的 OktaConfig :

public class OktaConfig
{
public string RedirectUrl { get; set; }
}

key 保管库中的 secret :

enter image description here

其他代码和你的一样。但在 Startup.cs 中,我使用下面的代码注入(inject) OktaConfig 并添加到 services:

services.AddSingleton<OktaConfig>(sp =>
{
var resultJson = Configuration.GetSection("<your secret name in kv>").Value;
return JsonConvert.DeserializeObject<OktaConfig>(resultJson);
});

Controller 中的代码:

private readonly ILogger<HomeController> _logger;
private OktaConfig oktaConfig;

public HomeController(ILogger<HomeController> logger , OktaConfig oktaConfig)
{
this.oktaConfig = oktaConfig;
_logger = logger;
}

public IActionResult Index()
{
return Ok(oktaConfig.RedirectUrl);
}

结果:

enter image description here

希望有帮助。

关于c# - 尝试从 Asp.net core 中的 Azure Key Vault 访问对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58316522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com