How to hard code credentials AWS SES JS SDK V3 - javascript

AWS forced me to upgrade do SDK V3, and now I'm having such a hard time setting up my credentials. They used to be hard-coded like:
AWS.config.update({
apiVersion: "2010-12-01",
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY",
region: "us-east-1",
});
But now the AWS package is deprecated in favor of the modularized #aws-sdk/client-ses.
How to hard code my credentials as I used to do in this new version of the SDK?
What I have so far:
import {
SESClient,
CloneReceiptRuleSetCommand,
} from "#aws-sdk/client-ses";
const client = new SESClient({
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY",
region: "us-east-1",
});
const command = new CloneReceiptRuleSetCommand(params);
client.send(command)
But it returns me the error "CredentialsProviderError: Could not load credentials from any providers"
P.S.: I know the disadvantages of hard-coding credentials, but this is not a issue for this application in particular. It's a backend Node.js service, and only I need to have access to it.

The key and the secret need to be in the credentials object of the configuration object.
Also, for CloneReceiptRuleSetCommand, you need to provide OriginalRuleSetName and RuleSetName.
So, it should be like this:
import {
SESClient,
CloneReceiptRuleSetCommand,
} from "#aws-sdk/client-ses";
const client = new SESClient({
credentials: {
accessKeyId: "MYKEY",
secretAccessKey: "MYOTHERKEY"
},
region: "us-east-1",
});
const params = {
OriginalRuleSetName: 'RULESET_TO_CLONE',
RuleSetName: 'TARGET_RULESET'
}
const command = new CloneReceiptRuleSetCommand(params);
client.send(command)
References:
Type definition for the SESClient constructor config
Type definition of the credentials object
Constructor definition of the CloneReceiptRuleSetCommand

Related

How to get the credentials using only Cognito Identity pool?

I'm looking to get temporary AWS credentials through the Cognito Identity pool. And then that credentials should access the AWS Transcribe service.
I've created an Identity pool and checked the option of unauthenticated user, so that I don't have to provide a token when I'm calling CognitoIdentityCredentials.
Then I attached the permission for transcribe service in the unauthenticated role(Cognito_TestIdentityPoolUnauth_Role-New).
But when I'm calling the CognitoIdentityCredentials, I'm not getting the credentials.
This is my code:-
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
// Configure the credentials provider to use your identity pool
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
identityPoolId: 'your_pool_id',
});
let accessKeyId, secretAccessKey, sessionToken;
// Make the call to obtain credentials
AWS.config.credentials.get(function(){
// Credentials will be available when this function is called.
accessKeyId = AWS.config.credentials.accessKeyId;
secretAccessKey = AWS.config.credentials.secretAccessKey;
sessionToken = AWS.config.credentials.sessionToken;
console.log('data', accessKeyId, secretAccessKey, sessionToken);
});
The acessKeyId, secretAccessKey and sessionToken is undefined. What am I missing here?
So to answer my own question. The latest credentials were somehow not being updated in the SDK. I'm also using the S3 service in the same function and the creds for that service are different. Here's the updated code which worked for me. And here's the thread that helped me.
const creds = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'identity_pool_id',
})
AWS.config.update({
region: 'us-east-1',
credentials: creds,
});
AWS.config.credentials.get(function () {
// Credentials will be available when this function is called.
const accessKeyId = AWS.config.credentials.accessKeyId;
const secretAccessKey = AWS.config.credentials.secretAccessKey;
const sessionToken = AWS.config.credentials.sessionToken;
console.log(accessKeyId, secretAccessKey, sessionToken);
});
PS:- Using node v14.

Error while calling AWS Athena using javascript code using Cognito UnauthRole with Full S3 and Athena Access

I am trying to query athena by assuming a role by using Cognito_IdedtityPool to get temporary accessKey, secretKey and sessionToken which has full Athena and S3 permission. But when i call it from my .js file it throws error
User:
Error : arn:aws:sts::<acc_no>:assumed-role/... is not authorized to perform: athena:StartQueryExecution on resource: arn:aws:athena:us-east-1:... because no session policy allows the athena:StartQueryExecution action
But once I create an IAM User and hardcode the keys with full Athena and S3 permission. then i am able to get data. Can anyone help in this ?
How can i query using assumed role ?
My js code is below :
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:<pool-id>',
});
var config = {
accessKey: credentials.accessKeyId, // REQUIRED
secretKey: credentials.secretAccessKey, //REQUIRED
sessionToken: credentials.sessionToken,// REQUIRED
region: 'us-east-1',
apiVersion: '2017-05-18',
}
AWS.config.update(config);
const AthenaExpress = require("athena-express"),
const athenaExpressConfig = {
aws: AWS,
s3: "s3://athena-output-destination/Test",
getStats: true,
workgroup: 'primary',
catalog: ATHENA_CATALOG,
retry: 4,
formatJson: true,
};
const athenaExpress = new AthenaExpress(athenaExpressConfig);
(async () => {
let myQuery = {
sql: query_string,
db: ATHENA_DB
};
try {
let results = await athenaExpress.query(myQuery);
console.log(results);
} catch (error) {
console.log(error);
}
})();

AWS Cognito with Angular 4: Error: Missing region in config

I'm developing a web application which uses AWS services backend size.
In this moment I use AWS Cognito to manage user sessions.
I'm developing the application with Angular 4 (using TypeScript / JavaScript language) and I found this useful class (In the JavaScript SDK for AWS Cognito) that should provide me with so many data that I need to display on the frontend:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html
The problem is that any method I invoke on this object, the console return this error:
Error: Missing region in config
at Request.VALIDATE_REGION (event_listeners.js:91)
at Request.callListeners (sequential_executor.js:105)
at callNextListener (sequential_executor.js:95)
at event_listeners.js:85
at finish (config.js:315)
at Config.getCredentials (config.js:360)
at Request.VALIDATE_CREDENTIALS (event_listeners.js:80)
at Request.callListeners (sequential_executor.js:101)
at Request.emit (sequential_executor.js:77)
at Request.emit (request.js:683)
I do not understand why this happens, because I have correctly configured the region, like this:
//Setting AWS credentials
AWS.config.region = environment.region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : environment.identityPoolId
});
and if i use the instruction console.log(AWS.config.region), the console prints the correct region.
Why it continues to visualize that error?
The complete code:
var params = {
UserPoolId: environment.clientId,
};
//Setting AWS credentials
AWS.config.region = environment.region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : environment.identityPoolId
});
this.cognitoidentityserviceprovider.listUsers(params, function(err, data) {
console.log(AWS.config.region)
if (err) console.log(err); // an error occurred
else console.log(data); // successful response
});
the path is always console.log(err) and the error is always Missing region in config. Why does this continue to happen?
How about if you do:
var CognitoIdentityServiceProvider = AWS.CognitoIdentityServiceProvider;
var client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region: 'us-east-1' });
and you call listUsers on the client object? I believe region should be passed along when you initialize the service client.
This question is from a while ago, but this worked for me:
When you load the AWS SDK in order to create the AWS instance, you probably have to set the region there, like this:
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-west-1',
});
function(){
var identityService = new AWS.CognitoIdentityServiceProvider({
apiVersion: '2016-04-18'
});
...
}
Note that you might also have to set your credentials, depending on the action. In this case, you can use code like this:
const AWS = require('aws-sdk');
AWS.config.update({
region: 'us-west-1',
accessKeyId: process.env.YOUR_ACCESSKEY,
secretAccessKey: process.env.YOUR_SECRETKEY
});
function(){
var identityService = new AWS.CognitoIdentityServiceProvider({
apiVersion: '2016-04-18'
});
...
}

How to pass httpOptions in aws-sdk DocumentClient constructor?

I am having serious performance issues with aws-sdk when I deploy my application to AWS.
I'm using it like below:
wrapper = {
accessKeyId: "YOURACCESSKEY",
secretAccessKey: "YOURSECRETKEY",
region: "us-east-1",
endpoint: new AWS.Endpoint('http://localhost:8000')
};
AWS.config.update(wrapper);
const docClient = new AWS.DynamoDB.DocumentClient();
module.exports ={"docClient":docClient};
I researched and found that - https://github.com/aws/aws-sdk-js/issues/900 - we can specify httpOptions in the aws so that keepAlive is enabled.
My questions is, how do I specify the httpOptions in the AWS-sdk constructor above:
var dynamo = new AWS.DynamoDB({
region: "ap-southeast-2",
httpOptions: {
agent: new https.Agent({
rejectUnauthorized: true,
keepAlive: true
})
}
});
how to add this to the wrapper config. It doesn't accept any extra httpOptions key in AWS.config.update
It should be something like this..
new AWS.DynamoDB.DocumentClient({
service: new AWS.DynamoDB({
region: "ap-southeast-2",
httpOptions: {
agent: new Https.Agent({ keepAlive: true })
}
})
})
It has to be added to DocumentClient, not the DynamoDB itself.

Node.js 303 Permanent Redirect when connecting to AWS-SDK

Good afternoon,
I'm trying to set up a connection to my aws product api, however I keep getting a 301 Permanent Redirect Error as follows:
{ [PermanentRedirect: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.]
message: 'The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.',
code: 'PermanentRedirect',
name: 'PermanentRedirect',
statusCode: 301,
retryable: false }
The code I am using to connect to the API is as follows:
var aws = require('aws-sdk');
//Setting up the AWS API
aws.config.update({
accessKeyId: 'KEY',
secretAccessKey: 'SECRET',
region: 'eu-west-1'
})
var s3 = new aws.S3();
s3.createBucket({Bucket: 'myBucket'}, function() {
var params = {Bucket: 'myBucket', Key: 'myKey', Body: 'Hello!'};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else
console.log("Successfully uploaded data to myBucket/myKey");
});
});
If I try using different regions, like us-west-1 I just get the same error.
What am I doing wrong?
Thank you very much in advance!
I have fixed this issue:
You have to make sure that you already have created a bucket with the same name; in this case, the name of the bucket would be 'myBucket'.
s3.createBucket({Bucket: 'myBucket'}, function() {
var params = {Bucket: 'myBucket', Key: 'myKey', Body: 'Hello!'};
Once you created the bucket, go to properties and see what region it is using - add this into:
aws.config.update({
accessKeyId: 'KEY',
secretAccessKey: 'SECRET',
region: 'eu-west-1'
})
Now it should work! Best wishes
I've just come across this issue and I believe the example at http://aws.amazon.com/sdkfornodejs/ is incorrect.
The issue with the demo code is that Bucket names should be in lowercase - http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
Had the demo actually output the err argument on the callback in s3.createBucket this would have been immediately obvious.
Also bucket names need to be unique in the region your creating them.
s3.createBucket({Bucket: 'mylowercaseuniquelynamedtestbucket'}, function(err) {
if(err){
console.info(err);
}else{
var params = {Bucket: 'mylowercaseuniquelynamedtestbucket', Key: 'testKey', Body: 'Hello!'};
s3.putObject(params, function(err, data) {
if (err)
console.log(err)
else
console.log("Successfully uploaded data to testBucket/testKey");
});
}
})
Was stuck on this for a while...
Neither setting the region name or leaving it blank in my configuration file fixed the issue. I came across the gist talking about the solution and it was quite simple:
Given:
var AWS = require('aws-sdk');
Prior to instantiating your S3 object do the following:
AWS.config.update({"region": "us-west-2"}) //replacing your region there
I was then able to call the following with no problem:
var storage = new AWS.S3();
var params = {
Bucket: config.aws.s3_bucket,
Key: name,
ACL:'authenticated-read',
Body: data
}
storage.putObject(params, function(storage_err, data){...})

Categories