I am building an environment which let users to run their nodejs code. It is pretty much like what Code Pen or runit does. If users need to run aws sdk code in the environment, I don't know how to handle their credentials and configs. I know aws nodejs sdk has a method config() which I can pass all configuration in. But usually developers aws credentials and config are saved in ~/.aws/credential and ~/.aws/config files. If I ask users to upload these files into the environment, how can I convert them into a parameter can be read by aws sdk? Is there a easy way to do or I have to manually parse these files?
- Can you include the code itselfLucas Hendren– Lucas Hendren2019-04-10 01:37:40 +00:00Commented Apr 10, 2019 at 1:37
- None of this sounds like a great idea to me from a security perspective. You should try hard to avoid asking for credentials like this.jarmod– jarmod2019-04-10 02:22:08 +00:00Commented Apr 10, 2019 at 2:22
- Maybe this can help you: stackoverflow.com/a/69921864/6491200Caio Santos– Caio Santos2021-11-11 00:36:23 +00:00Commented Nov 11, 2021 at 0:36
3 Answers
You can do it like this:
const AWS = require('aws-sdk'); // config.json {"accessKeyId": <YOUR_ACCESS_KEY_ID>, "secretAccessKey": <YOUR_SECRET_ACCESS_KEY>, "region": "us-east-1" } AWS.config.loadFromPath('./config.json'); You can also do it like this:
var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", "accessKeyId": <YOUR_ACCESS_KEY_ID>, "secretAccessKey": <YOUR_SECRET_ACCESS_KEY> }); 1 Comment
Here's an example of hard-coding credentials for the Simple Email Service (SES) in AWS SDK v3:
let { SES } = require("@aws-sdk/client-ses"); const ses = new SES({ apiVersion: "2010-12-01", region: "us-west-1", credentials: { accessKeyId: ".....", secretAccessKey: ".....", }, }); I'm guessing it's basically the same for other AWS constructors - i.e. just add that credentials property with the access keys in it.
(Note that hard-coding your credentials like this convenient, but can be a bad idea for professional/production applications where security is important. See the links at the bottom of this page for several other approaches that are more secure.)
Comments
You definitely DON'T want to save your AWS credentials in the file. A better way to do it would be to save the values in an environment variable in the environment your app is going to be running on. If you have the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables set, the SDK will automatically load them, and you don't have to worry about it in your code, as described here: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-environment.html Depending on which services you are using, these values might already be set. If not, it should be pretty easy to create a user or role that has permissions for whatever operations you are using the SDK for.