简体   繁体   English

从 AWS Secret Manager 访问密钥

[英]Access secret key from AWS Secret Manager

My Secret Stored look like this我的秘密存储看起来像这样

Secret Manager秘密经理

SecretName: MultipleKeySecretName SecretName:MultipleKeySecretName

{
  "Key1": "Key1 Value",
  "Key2": "Key2 Value"
}

SecretName: SingleSecretName秘密名称:单秘密名称

{
  "Key1": "Key1 Value"
}

I have shared package where there is a common code which retrieve AWS Secret Values.我分享了 package ,其中有一个检索 AWS 秘密值的通用代码。

 public async Task<string> GetValue(string key)
    {
        Requires.ArgumentNotNullOrWhitespace(key, "key");
        var region = RegionEndpoint.GetBySystemName(CurrentRegion);

        if (region == null)
        {
            logger.LogError($"Unable to retrieve key because region is not specified by application");
            throw new ArgumentNullException("Unable to retrieve key because region is not specified by application");
        }

        try
        {
            var secretsManager = new AmazonSecretsManagerClient(region);
            var request = new GetSecretValueRequest
            {
                SecretId = key
            };
            var getSecretValueResponse = await secretsManager.GetSecretValueAsync(request);

            if (getSecretValueResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                logger.LogError($"Unable to find secret with keyname : {key} in secret manager");
                throw new ArgumentNullException($"Unable to find secret with keyname : {key} in secret manager");
            }

            var secretStringJson = getSecretValueResponse.SecretString;
            return JsonConvert.DeserializeObject<Dictionary<string, string>>(secretStringJson).Values.FirstOrDefault();
        }
        catch (Exception exception)
        {
            logger.LogError($" An error occurred getting value from secret manager for" +
                   $" Key :{key} Region : {region} {exception.Message}");
            throw;
        }
    }

I consumed this above code like this when I had single secertkeys in one secret当我在一个秘密中有单个密钥时,我像这样使用了上面的代码

var mysingleKey =  GetValue("SingleSecretName").Result; //Work perfect for single scenearios

Now I have multiple keys with same secret see above.现在我有多个具有相同秘密的密钥,见上文。

var multipleValues =  GetValue("MultipleKeySecretName").Result

as per the current implementation it will always bring first value.根据当前的实现,它总是会带来第一个价值。 I can change the shared package to get Dictionary of values.我可以更改共享的 package 以获取值字典。

  1. How do get each key separately with above code如何使用上面的代码分别获取每个密钥
    Is this possible (GetValue("SingleSecretName.Key1").Result?这可能吗 (GetValue("SingleSecretName.Key1").Result?
  2. What is the best way to get multiple keys with one single call to AWS Secret Manager?通过一次调用 AWS Secret Manager 来获取多个密钥的最佳方法是什么?
    Getting all values in shared code and get the value from the dictionary?获取共享代码中的所有值并从字典中获取值?

The problem with your code is that you are assuming there is just one item in the dictionary, and always returning it.您的代码的问题是您假设字典中只有一项,并且总是返回它。 If you really want to just get the one item from the dictionary you need to specify the secretId (you were calling this key ) as well as the dictionary key .如果您真的只想从字典中获取一项,则需要指定secretId (您正在调用此key )以及字典key Then you can look for that key in the result.然后您可以在结果中查找该键。 Something like this:像这样的东西:

public async Task<string> GetValueAsync(string secretId, string key)
    {
        Requires.ArgumentNotNullOrWhitespace(secretId, "secretId");
        Requires.ArgumentNotNullOrWhitespace(key, "key");
        var region = RegionEndpoint.GetBySystemName(CurrentRegion);

        if (region == null)
        {
            logger.LogError($"Unable to retrieve key because region is not specified by application");
            throw new ArgumentNullException("Unable to retrieve key because region is not specified by application");
        }

        try
        {
            var secretsManager = new AmazonSecretsManagerClient(region);
            var request = new GetSecretValueRequest
            {
                SecretId = secretId
            };
            var getSecretValueResponse = await secretsManager.GetSecretValueAsync(request);

            if (getSecretValueResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                logger.LogError($"Unable to find secret with secretId : {secretId} in secret manager");
                throw new ArgumentException($"Unable to find secret with secretId : {secretId} in secret manager");
            }

            var secretStringJson = getSecretValueResponse.SecretString;
            var secret = JsonConvert.DeserializeObject<Dictionary<string, string>>(secretStringJson);

            if (secret.ContainsKey(key))
            {
                return secret[key];
            }
            else 
            {
                logger.LogError($"Unable to find key within secret : {key}");
                throw new ArgumentException($"Unable to find key within secret : {key}");
            }
        }
        catch (Exception exception)
        {
            logger.LogError($" An error occurred getting value from secret manager for" +
                   $" Key :{key} Region : {region} {exception.Message}");
            throw;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM