A few years ago I used the following code to authenticate an ASP .NET website using AWS Cognito, but it probably wasn’t the best solution putting the keys in the compiled code. I’m curious what is the recommended way to do this? Should Identity Center be used instead? Or should I use a credential file? And how would I handle putting the credentials on a production server?
string accessKey = "xxxxxxxxxx";
string secretKey = "xxxxxxxxxxx";
string poolId = Environment.GetEnvironmentVariable("cognito_pool_id");
string clientId = Environment.GetEnvironmentVariable("app_client_id");
string clientSecret = Environment.GetEnvironmentVariable("app_client_secret");
var awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
var cognitoClient = new AmazonCognitoIdentityProviderClient(awsCredentials, RegionEndpoint.USEast1);
var userPool = new CognitoUserPool(poolId, clientId, cognitoClient, clientSecret);
builder.Services.AddCognitoIdentity();
builder.Services.AddSingleton<IAmazonCognitoIdentityProvider>(cognitoClient);
builder.Services.AddSingleton<CognitoUserPool>(userPool);
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
builder.Services
.ConfigureApplicationCookie(o =>
{
o.Cookie.HttpOnly = true;
o.ExpireTimeSpan = TimeSpan.FromHours(1);
o.SlidingExpiration = true;
o.LoginPath = "/Identity/Account/Login";
o.LogoutPath = "/Identity/Account/Logout";
});
2
Answers
Is your website running on AWS EC2? If yes, you shouldn’t be using credentials at all – you should be using IAM Role. In such case, you can simply call
If you are not running on EC2 – you have to store credentials somewhere! Yes, code is worst case – you need to recompile code every time they change, and you run the risk of exposing it through version control, etc. There are other ways – we use IIS environment variables; or maybe appsettings.json (but again, there is a risk of exposing through repository)
The access key and secret key are generally used server side. If you have server side code running in a lambda to api gateway, the sdk can be authenticated with an IAM service role attached to the lambda.
Then you can send to api gateway a post request only with the info needed to authenticate from your front end website.
This is normally a web request from C#.