【发布时间】:2021-09-03 22:12:40
【问题描述】:
我有一个在 EC2 实例上运行的 .Net Core 应用程序。 我想使用 Secrets Manager 来包含我的 Web 应用程序的秘密,例如“连接字符串”等。 AWS Secrets Manager 文档不是很有用,我似乎找不到一个教程来展示/解释如何在 EC2 上使用 Secrets Manager。
我已经能够使用邮递员并使用以下代码成功提取“秘密”: 但是 Access Key 和 Secrets Key 都是硬编码的。
我不希望出现这种情况。 我已安装 SDK 并将访问密钥和密钥加载到此配置文件中。
基本上我的问题是如何从 SDK 中提取访问密钥和秘密密钥来签署请求?
if (secretsDetail == null)
{
return "Please provide SecretsDetails.";
}
string secretName = "";
string secret = "";
MemoryStream memoryStream = new MemoryStream();
AmazonSecretsManagerConfig amazonSecretsManagerConfig = new AmazonSecretsManagerConfig();
amazonSecretsManagerConfig.ServiceURL = secretsDetail.ServiceURL;
IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName("eu-west-2"));
GetSecretValueRequest request = new GetSecretValueRequest();
request.SecretId = secretName;
request.VersionStage = secretsDetail.VersionStage == null ? "AWSCURRENT" : secretsDetail.VersionStage; // VersionStage defaults to AWSCURRENT if unspecified.
GetSecretValueResponse response = null;
try
{
response = client.GetSecretValueAsync(request).Result;
}
catch (DecryptionFailureException)
{
// Secrets Manager can't decrypt the protected secret text using the provided KMS key.
// Deal with the exception here, and/or rethrow at your discretion
throw;
}
catch (InternalServiceErrorException)
{
// An error occurred on the server side.
// Deal with the exception here, and/or rethrow at your discretion
throw;
}
catch (InvalidParameterException)
{
// You provided an invalid value for a parameter.
// Deal with the exception here, and/or rethrow at your discretion
throw;
}
catch (InvalidRequestException)
{
// You provided a parameter value that is not valid for the current state of the resource.
// Deal with the exception here, and/or rethrow at your discretion.
throw;
}
catch (ResourceNotFoundException)
{
// We can't find the resource that you asked for.
// Deal with the exception here, and/or rethrow at your discretion.
throw;
}
catch (System.AggregateException)
{
// More than one of the above exceptions were triggered.
// Deal with the exception here, and/or rethrow at your discretion.
throw;
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (response.SecretString != null)
{
return secret = response.SecretString;
}
else
{
memoryStream = response.SecretBinary;
StreamReader reader = new StreamReader(memoryStream);
string decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
return decodedBinarySecret;
}
【问题讨论】:
标签: amazon-web-services amazon-ec2 aws-secrets-manager