Trying to call cognito token from postman script - node.js

Working within Postman I'm trying to call a jwtToken from Cognito using node's aws-sdk but I'm getting the following error:
There was an error in evaluating the Pre-request Script: Error: Cannot find module 'aws-sdk'
This is my scrypt:
const AWS = require('aws-sdk');
var authenticationData = {
Username: 'username',
Password: 'password',
};
var authenticationDetails = new
AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId: 'us-east-1_xxxxxx',
ClientId: 'xxxxx'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: 'username',
Pool: userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
var accessToken = result.getAccessToken().getJwtToken();
var idToken = result.idToken.jwtToken;
},
});
pm.globals.set("token", idToken);
So far the only commands I ran where: brew install node
 and npm install aws-sdk
I'm sure I'm missing some sort of configuration to call the module, Any help will do! Thnx!

Seems like Postman Sandbox cannot obtain a script's external dependencies.
You can leverage eval() Javascript function to import additional Javascript code by having the code stored within a postman global or environment variable.
Example: eval(postman.getGlobalVariable('aws-sdk-code'))
See TIP #5: http://blog.getpostman.com/2017/07/28/api-testing-tips-from-a-postman-professional/
Also, you might encounter a later issue once the code executes as it seems you are requesting for AmazonCognitoIdentity class in the amazon-cognito-identity-js package.
https://www.npmjs.com/package/amazon-cognito-identity-js

Related

how to create a postgresql instance using OAuth2Client in google using nodejs client library

i have a requirement for creating PostgreSQL instance using google SQL admin API, for the authentication, i want to use OAuth2Client in node js client library
function first() {
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
var tkn = await oAuth2Client.getToken(code_from_another_user);
oAuth2Client.setCredentials(tkn);
return oAuth2Client;
});
function second(oAuth2Client)
{
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: oAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
function mainexec()
{
var a = first();
var b = second(a);
});
and i get this error
Error: No access, refresh token, API key or refresh handler callback
is set
here actually, i am trying to create a PostgreSQL instance on other google account cloud platform with there consent using OAuth2Client access token method. anyone please help? any supporting documentation?.
The function first returns oAuth2Client as it is . But in the function second it is converted to JSON object automatically.
so changed the function named second like this
function second(oAuth2Client)
{
var newoAuth2Client = new google.auth.OAuth2(
oAuth2Client._clientId,
oAuth2Client._clientSecret,
oAuth2Client.redirectUri
);
var tokenObj = {
access_token: oAuth2Client.credentials.tokens.access_token,
refresh_token: oAuth2Client.credentials.tokens.refresh_token,
};
newoAuth2Client.credentials = tokenObj;
var req = {
project: prjName,
resource: {
databaseVersion: "POSTGRES_13",
name: name,
region: cregion ,
gceZone: czone,
settings: {*****}
rootPassword: "xxxxx",
},
auth: newoAuth2Client,
};
var crpsql = await sqlAdmin.instances.insert(req);
return crpsql;
});
it worked like a magic.

Cant disconnect from xero using xero.disconnect

Im using AdonisJs as my Node Framework, the xeroclient config works perfectly, I can extract details that I need.
I just cant disconnect, as I saw in their sample app we just have to call xero.disconnect, yet i am receiving an error xero.disconnect is not a function
im using the xero-node npm package
const xeroNode = require('xero-node')
const xero = new xeroNode.XeroClient({
clientId: Config.get('xero.client_id'),
clientSecret: Config.get('xero.client_secret'),
redirectUris: [Config.get('xero.redirectUri')],
scopes: Config.get('xero.scopes').split(" ")
})
async disconnect ({ response, session }) {
...
await xero.disconnect(xero.tenantIds[0])
...
}
Only thing that looks incorrect is the parameter you are passing to the function. That should actually be the connection object's ID not the tenantId itself: await xero.disconnect(xero.tenants[0].id)
But other than that can you elaborate the package version you are using? I've just mimicked everything about how you are importing and setting up client, so it's unclear why the disconnect function is not available. Please ensure you are using the most recent version 4.6.0 - the following just worked for me after I successfully got my access token back from the /callback flow.
Setup:
const xeroNode = require('xero-node')
const xero = new xeroNode.XeroClient({
clientId: client_id,
clientSecret: client_secret,
redirectUris: [redirectUrl],
scopes: scopes.split(' '),
});
/connect
const consentUrl: = await xero.buildConsentUrl();
/callback
const tokenSet = await xero.apiCallback(returning_url);
await xero.updateTenants();
/disconnect
const connection = xero.tenants[0]
await xero.disconnect(connection.id)
If you can post/log some more info can get this sorted for you!

If MFA enabled in AWS cognito, do I need to create js on client side to call cognitoUser.authenticateUser() because of the promt for code?

I am using reactjs and node for server side.
As you can see in the "mfa required" part of the code below, if this is all on node, then I can't really do "prompt" the user for the code, I have to pass this back to the front end.
Tried solution: If I do pass the MFA required to front end and get the users input then send it back to node to call "respondToAuth" I am getting two MFA codes in my SMS message.
Have I tried other solutions?
I am hesitant to use amplify because everything is on the front end, I would ideally like to do my authentication on the back end (thus node).
Another option I am leaning towards is just using initiateAuth api instead of "cognitoUser.AuthenticateUser". This way I can get the challenge response and pass it on in sequence. But as per my initial question, I am wondering if I can implement the below code and be able to route users to input MFA code (without duplicating MFA sms message)
AWS.config.update({
region: process.env.Region
});
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const poolData = { //--Moved to env variables
UserPoolId: process.env.UserPoolId, // your user pool id here
ClientId: process.env.ClientId // your app client id here
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
router.post('/api/authenticateuser', (req, res) => {
const val = req.body;
var userData = {
Username: val.value.user, // your username here
Pool: userPool
};
var authenticationData = {
Username: val.value.user, // your username here
Password: val.value.pass, // your password here
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('You are now logged in.');
console.log(result);
const accessToken = result.getAccessToken().getJwtToken();
const idToken = result.getIdToken().getJwtToken();
res.json({
accessToken,
idToken
});
},
onFailure: function(err) {
res.json(err);
},
mfaRequired: function(codeDeliveryDetails) {
// console.log("mfa enabled");
// var verificationCode = prompt('Please input verification code' ,'');
// cognitoUser.sendMFACode(verificationCode, this);
// res.json({ MFA:codeDeliveryDetails})
}
});
})

Using AWS Cognito in a Lambda function with npm

I'm trying to use AWS Cognito in a Lambda function to authorize a user.
I have some sample code from a Udemy Course (no longer available): https://www.udemy.com/minimum-viable-aws-cognito-user-auth-in-javascript
The code uses the script files:
aws-cognito-sdk.min.js
amazon-cognito-identity.min.js
The second seems to available by npm as: amazon-cognito-identity-js
The first file is supposed to be a cut down version of the aws-sdk with just the Cognito api components. The full aws-sdk is available from npm as: aws-sdk but I cannot find the cutdown version in npm.
Is the cutdown file: aws-cognito-sdk.min.js available in npm?
EDIT:
According to Russell I should use the aws-sdk package.
So if I have code:
const AWS = require('aws-sdk');
var authenticationDetails = new AWS.AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
I get the error:
Cannot read property 'CognitoIdentityServiceProvider' of undefined
What is the correct path to AuthenticationDetails?
For Lambdas use the aws-sdk module as such:
const { CognitoIdentityServiceProvider } = require('aws-sdk')
//or
const CognitoIdentityServiceProvider = require('aws-sdk/clients/cognitoidentityserviceprovider') // Much smaller size
For authentication use the AdminInitiateAuth method.
const cognitoProvider = new CognitoIdentityServiceProvider({
apiVersion: '2016-04-18',
accessKeyId:...
secretAccessKey: ...
region:...
})
await cognitoProvider.adminInitiateAuth(...)
The amazon-cognito-identity-js package is meant for frontend clients (React, React Native, etc). It contains only the functionality necessary to connect to Cognito. It does not require the aws-sdk module (unless you need extra features).
While you may be able to use the amazon-cognito-identity-js for your use case it's far from ideal as you are just pretending to be an unauthenticated user with limited functionality compared to loading the admin method using your api key thereby providing you with much more functionality.
Got this working.
package.json needs dependencies:
"amazon-cognito-identity-js": "^1.31.0",
"aws-sdk": "^2.182.0",
AWS Lambda does not use Javascript ES6 and so you can't use the 'import' keyword.
const AWS = require('aws-sdk');
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var AuthenticationDetails = AmazonCognitoIdentity.AuthenticationDetails;
var CognitoUser = AmazonCognitoIdentity.CognitoUser;
var poolData = {
UserPoolId: 'THE USER POOL ID',
ClientId: 'THE CLIENT ID'
};
var userPool = new CognitoUserPool(poolData);
AWS.config.region = 'AWS_REGION';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'THE USERPOOL ID',
});
var email = "someone#somewhere.com";
var password = "password";
var authenticationData = {
Username: email,
Password: password
};
var authenticationDetails = new AuthenticationDetails(authenticationData);
var userData = {
Username: email,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
console.log(result);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
callback(null, result);
},
onFailure: function (err) {
console.log('Login error: ' + err);
callback(null, result);
}
});
I believe you are referring to the amazon-cognito-identity-js npm package here:
https://www.npmjs.com/package/amazon-cognito-identity-js
The NPM package includes both files.
The package includes the cognito SDK calls (aws-cognito-sdk). It also depends on the core AWS SDK.

nodejs googleapis, authClient.request is not a function

I am creating an oauth2client in one function like so and returning it. I actually do pass in the clien id, secret, redirect url, and credentials. Those are all correct from what I have checked.
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
...
credentials = {
access_token: accessToken,
refresh_token: refreshToken
};
oauth2Client.setCredentials(credentials);
I then do this in the function where the oauth2client object is returned:
var plus = google.plus('v1');
console.log(JSON.stringify(oauth_client));
plus.people.get({ userId: 'me' , auth: oauth_client}, function(err, response) {
if(err) {
console.log(err);
} else {
console.log(JSON.stringify(response));
return response;
}
});
However I then get an error message saying that authClient.request is not a function.
TypeError: authClient.request is not a function
at createAPIRequest (/node_modules/googleapis/lib/apirequest.js:180:22)
I'm not sure why I get this error. I also did console.log(JSON.stringify(oauth_client)) to check for a request function and I didn't see any. Someone mentioned that this can't display the full prototype chain and that the request function might actually be there.
The problem is with "oauth_client".I used "google-auth-library" to authenticate.
var googleAuth = require('google-auth-library');
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = credentials;
and then use this oauth2Client as oauth_client.
Not sure if you ever resolved this but try checking the scopes you have permissions for.
I was getting this error and turns out I had my scope set to 'https://www.googleapis.com/auth/youtube.readonly' and then when I changed my scope to 'https://www.googleapis.com/auth/youtube.upload' & 'https://www.googleapis.com/auth/youtube' I was able to upload videos instead of getting the error authClient.request is not a function

Resources