Configuring AWS Secrets Manager
AWS Secrets Manager helps you protect the secrets that you need to access your applications, services, and IT resources. The service securely stores, manages, encrypts, and rotates database credentials, API keys, and other secrets, including OAuth tokens, and provides native integration with Amazon Relational Database Service (Amazon RDS), Amazon Redshift, and Amazon DocumentDB. Users and applications retrieve secrets by calling Secrets Manager APIs, which eliminates the need to hardcode sensitive information in plaintext. Secrets Manager includes fine-grained access control permissions and provides a centralized location to audit secrets rotation in AWS Cloud, on-premises, and third-party environments.
Prerequisites for using Secrets Manager with .NET Framework applications
-
An active AWS account
-
Microsoft Visual Studio
, installed -
AWS Command Line Interface (AWS CLI) version 2, installed and configured to access your AWS account (see instructions)
-
AWS Toolkit for Visual Studio, configured (see instructions)
-
A secret, created and retrieved by using the Secrets Manager console or the AWS CLI (see instructions)
Example
To access secrets from Secrets Manager in the ASP.NET Core web API (.NET 6):
-
Add the following NuGet package to the ASP.NET Core web API.
AWSSDK.SecretsManager.Caching
-
In the
Program.cs
file, make the following changes.-
Add the
Amazon.SecretsManager
namespace (1).using Amazon.SecretsManager;
-
Register the service (2).
builder.Services.AddScoped<IAmazonSecretsManager>(x => new AmazonSecretsManagerClient(RegionEndpoint.EUWest2) );
-
-
To retrieve the secrets from Secrets Manager, make the following changes to the controller class file (for example,
ValuesController.cs
).-
Add the constructor (1).
private readonly IAmazonSecretsManager _secretsManager; public SecretsController(IAmazonSecretsManager secretsManager) { _secretsManager = secretsManager; }
-
Implement the
GetSecret
method (2).string secretName = "arn:aws:secretsmanager:eu-west-2:111122223333:secret:dev/myapp/tenant-gSj6qd"; GetSecretValueRequest request = new GetSecretValueRequest(); request.SecretId = secretName; request.VersionStage = "AWSCURRENT"; Task<GetSecretValueResponse> response = _secretsManager.GetSecretValueAsync(request); return Ok(new { Secret = response.Result.SecretString });
where 111122223333 refers to the account ID.
Note
secretName
refers to the name or Amazon Resource Name (ARN) of the secret. After a secret is created, this value can be retrieved from the Secrets Manager console. You should callsecretName
dynamically or from environment variables. Do not hardcode this value in production environments. -