-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathKeyVaultAccess.cs
83 lines (80 loc) · 3.38 KB
/
KeyVaultAccess.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace DocumentTranslationService.Core
{
public class KeyVaultAccess
{
public string KeyVaultName { get; init; }
public KeyVaultAccess(string keyVaultName)
{
KeyVaultName = keyVaultName;
}
/// <summary>
/// Retrieve the Translator credentials from the key vault
/// Caller should catch the Azure.RequestFailed exception.
/// </summary>
/// <returns cref="DocTransAppSettings">DocTransAppSettings class</returns>
/// <exception cref="KeyVaultAccessException"/>
public async Task<DocTransAppSettings> GetKVCredentialsAsync()
{
string VaultUri;
if (KeyVaultName.Contains('.')) VaultUri = KeyVaultName;
else VaultUri = "https://" + KeyVaultName + ".vault.azure.net/";
SecretClient client = new(new Uri(VaultUri), new InteractiveBrowserCredential());
List<string> secretNames = new() { "AzureRegion", "DocTransEndpoint", "StorageConnectionString", "ResourceKey", "TextTransEndpoint" };
List<Task<Azure.Response<KeyVaultSecret>>> tasks = new();
Azure.Response<KeyVaultSecret>[] kvSecrets;
foreach (string secret in secretNames) tasks.Add(client.GetSecretAsync(secret));
try
{
kvSecrets = await Task.WhenAll(tasks);
}
catch (CredentialUnavailableException ex)
{
Debug.WriteLine($"Azure Key Vault: {ex.Message}\nPlease log in to your work or school account.");
throw new KeyVaultAccessException("msg_NotLoggedIn", ex);
}
catch (Azure.RequestFailedException ex)
{
Debug.WriteLine($"Azure Key Vault: {ex.Message}");
throw new KeyVaultAccessException("msg_KeyVaultRequestFailed", ex);
}
catch (Exception ex)
{
Debug.WriteLine($"Azure Key Vault: {ex.Message}");
throw new KeyVaultAccessException("msg_KeyVaultRequestFailed", ex);
}
DocTransAppSettings settings = new();
foreach (var kvSecret in kvSecrets)
{
switch (kvSecret.Value.Name)
{
case "AzureRegion":
settings.AzureRegion = kvSecret.Value.Value;
break;
case "DocTransEndpoint":
settings.AzureResourceName = kvSecret.Value.Value;
break;
case "StorageConnectionString":
settings.ConnectionStrings ??= new();
settings.ConnectionStrings.StorageConnectionString = kvSecret.Value.Value;
break;
case "ResourceKey":
settings.SubscriptionKey = kvSecret.Value.Value;
break;
case "TextTransEndpoint":
settings.TextTransEndpoint = kvSecret.Value.Value;
break;
default:
break;
}
}
settings.AzureKeyVaultName = KeyVaultName;
return settings;
}
}
}