I have already used:
user-secret set "AWSAccessKey" "my access key" and
user-secret set ""AWSSecretKey" "my secret key"
to get my keys into the secret store.
I’ve got this class that I will be using to send email via Amazon SES, but I don’t know how to get my keys into it.
public class MailHelper
{
public void SendEmailSes(string senderAddress, string receiverAddress, string subject, string body)
{
using (var client = new AmazonSimpleEmailServiceClient(
new BasicAWSCredentials("[AWSAccessKey]", "[AWSSecretKey]"),
RegionEndpoint.USEast1))
{
var sendRequest = new SendEmailRequest
{
Source = senderAddress,
Destination = new Destination { ToAddresses = new List<string> { receiverAddress } },
Message = new Message
{
Subject = new Content(subject),
Body = new Body { Text = new Content(body) }
}
};
var response = client.SendEmail(sendRequest);
}
}
}
What do I put in my Startup.cs in order to get those keys available in my MailHelper class? What needs to be added to the MailHelper class itself?
I’ve seen some examples for MVC Controllers, but I couldn’t find anything for custom utility classes that are not already implementing some expected interface.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
A class for your settings:
public class AwsSettings
{
public string AccessKey { get; set; } = string.Empty;
public string AccessSecret{ get; set; } = string.Empty;
}
if your settings were in config.json you would do it like this:
{
"AwsSettings": {
"AccessKey": "yourkey",
"AccessSecret": "yoursecret"
}
}
in Startup you would need this:
services.Configure<AwsSettings>(Configuration.GetSection("AwsSettings"));
your mailer class would need the settings injected into constructor
using Microsoft.Framework.OptionsModel;
public class MailHelper
{
public MailHelper(IOptions<AwsSettings> awsOptionsAccessor)
{
awsSettings = awsOptionsAccessor.Options;
}
private AwsSettings awsSettings;
... your other methods
}
UserSecrets is just another configuation source so instead of config.json you can put the settings there but you need to simulate the structure so it can map to your class so you set them like this with colons:
user-secret set "AwsSettings:AccessKey" "my access key" and user-secret set "AwsSettings:AccessSecret" "my secret key"
that is equivalent to the structure I showed for config.json
now the settings will be loaded from user secrets and injected into your mailer
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0