How to Get AccessToken Dynamically from Cognito OAuth2.0 in Electron JS - amazon-web-services

Hello i use Electron JS for a desktop app which is related to a cloud plateform from which in needto get a list of Patients.
As far as now i can get it but with a static AccessToken. I really struggled to get it dynamic, please help.
Here is my code :
This is my configuration file where i specify Cognito Parameters :
export default {
s3: {
REGION: 'YOUR_S3_UPLOADS_BUCKET_REGION',
BUCKET: 'YOUR_S3_UPLOADS_BUCKET_NAME',
},
apiGateway: {
REGION: 'YOUR_API_GATEWAY_REGION',
URL: 'YOUR_API_GATEWAY_URL',
},
cognito: {
REGION: 'eu-west-1',
USER_POOL_ID: 'eu-west-1_P0Jcr7nig',
APP_CLIENT_ID: '4m1utu56hjm835dshts9jg63ou',
IDENTITY_POOL_ID: 'YOUR_IDENTITY_POOL_ID',
authenticationFlowType: 'USER_PASSWORD_AUTH',
AUTHENTICATION_FLOW_TYPE: 'USER_PASSWORD_AUTH',
},
API: {
endpoints: [
{
name: 'PatientsList',
endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients',
//endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage',
},
],
},
};
Auth.signIn({
username: process.env.username,
password: process.env.password,
}).then().catch(err => {
console.log(err)});
In another file this is my getaccesstoken function which i export to the main
function getAccessToken() {
const poolData = {
UserPoolId : COGNITO_USER_POOL_ID,
ClientId : COGNITO_CLIENT_ID,
};
const userPool = new CognitoUserPool(poolData);
var authenticationData = {
Username : process.env.username, // your username here
Password : process.env.password, // your password here,
authenticationFlowType: process.env.AUTHENTICATION_FLOW_TYPE,
Pool : userPool
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData);
var cognitoUser = new CognitoUser(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
},
onFailure: function(err) {
console.log(err);
},
});
}
And finally here is how i get the data in main :
The declarations :
const { Auth } = require('./cognitoAuth');
const theAccessToken = require('./cognitoAuth');
The code :
//Get Data From Cloud ECS
const API_URL = 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients';
const headers = {
"Content-Type": "application/json",
//Authorization: theAccessToken.getAccessToken()
Authorization: "eyJraWQiOiJBbE1DZnBCTHYyVUlNazhXSG4xaTk4RG1QNlFmcFpSSjFaSW1qcVVFZnVBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI4OWYyZGMxZi1iMTI3LTQzM2QtODJhYS1iMjNkNWJhNzY5NGEiLCJjb2duaXRvOmdyb3VwcyI6WyJkb2N0b3IiXSwiZXZlbnRfaWQiOiI1OTM0ZmIwNC0yYTUzLTQ2NmQtYTU1Ni0zNTM3M2RhZmU1Y2UiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2VyLmFkbWluIiwiYXV0aF90aW1lIjoxNTk1NDI2NjQ2LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAuZXUtd2VzdC0xLmFtYXpvbmF3cy5jb21cL2V1LXdlc3QtMV9QMEpjcjduaWciLCJleHAiOjE1OTcxNTUxMDUsImlhdCI6MTU5NzE1MTUwNSwianRpIjoiNGRkN2U5ZGUtYmQ2YS00NTg4LWIzZDAtMTVjMWM1NWQxY2Y2IiwiY2xpZW50X2lkIjoiNG0xdXR1NTZoam04MzVkc2h0czlqZzYzb3UiLCJ1c2VybmFtZSI6Ijg5ZjJkYzFmLWIxMjctNDMzZC04MmFhLWIyM2Q1YmE3Njk0YSJ9.LYvzPRBxvKw2P3gHwV8NhYPg_EB3F7ZK2F5HpRWHtBHksr6D4N5Fw56ZVupkRCxVJSq0f93DdljI7BBcBnp9d_hpLzmJLTfBhA3t870omTxalTqpGXN_SvsZmuwcfCX-awn1Um6x_-fhq3zcfPkB9FBljbtwPN-kvCc-Iynei9anVxXI686nIbkfbYfnuRnHrbY0vg8FtyDIDBMv277FPoJ96NwPD4mJvNBxQHi_KfWxQ1DmLiAC6c_l2jP_wawAPBv788CjD_8OlKBbjAHinGEkaL1K9vjI5MhNPyTA5ym1IaWar7Jr8RkUDzQGvqEUPKoOUe9PswmOOxLBjehMgQ"
};
//console.log('Token Value:', theAccessToken.getAccessToken());
const getPatients = async(API_URL) => {
try {
//get data from cloud specifiying get method and headers which contain token
const response = await fetch(API_URL,{
method: 'GET', headers: headers}
);
var listPatients = await response.json();
listPatients.items.forEach(patient => {
//Checking what i got
console.log(patient);
});
} catch(err) {
console.log("Error" + err);
}
};
getPatients(API_URL);
Now when i make it dynamic by specifying theAccessToken.getAccessToken
I get this error, USER_SRP is not enabled even if specify it, when i asked team told me the cloud service doesn't want to enable it.
So how can i get this access token please?

For a desktop app it is recommended to do these 2 things, according to security guidance:
Use Authorization Code Flow (PKCE)
Login via the system browser, so that the app never sees the user's password
I have a couple of Electron code samples that use Cognito, which you can easily run - maybe start here:
First desktop app

Related

Postman Pre-Request Script AWS Cognito Token Invalid Grant

This has me stumped.
I have a cognito pool with a resource server, one custom scope and one app client (clientid and secret).
I have my (pre-request) script set up in Postman like this
const clientId = pm.environment.get("cognitoClientId");
const clientSecret = pm.environment.get("cognitoClientSecret");
const grantType = "client_credentials";
const tokenUrl = pm.environment.get("cognitoAuthTokenURL");
const postRequest = {
url: tokenUrl,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{
key: "grant_type",
value: grantType
},
{
key: "client_id",
value: clientId
},
{
key: "client_secret",
value: clientSecret
},
{
key: "scope",
value: "myResourceServer/myResource.list"
}
]
}
};
pm.sendRequest(
postRequest
,(error, response) => {
console.log("Callback fired");
console.log(error);
console.log(response);
}
);
It fails on the response body with the following error:
{"error":"invalid_grant"}
From the AWS Documentation I get
Refresh token has been revoked
Which makes no sense as I am not requesting a refresh token
What am I doing wrong here, or where should I be looking?

AWS API Gatway (Proxy) with Lambda - Thworing internal server error

I am working on a custom auth solution, I backend is on NODE (lambda) and calling that lambda by API gateway (it's a post-call).
For every thin is working fine if I use no-Proxy APIs, but in my case in need to pass custom additional headers. And when I tried with prox it is not responding. (it look like Cognito async call takes time or response is not resolving)
I am not sure I am missing some configuration or something wrong with code (code is working fine individual lambda and with API without Proxy).
here is my Lambda code.
// const AWS = require("aws-sdk");
// var crypto = require("crypto-js");
var CryptoJS = require("crypto-js");
var Crypto = require("crypto");
const { CognitoIdentityServiceProvider } = require("aws-sdk");
const hashSecret = (clientSecret, username, clientId) =>
Crypto.createHmac("SHA256", clientSecret)
.update(username + clientId)
.digest("base64");
async function isUserValid() {
const USER_POOL_ID = "poolid";
const CLIENT_ID = "clidntID";
const CLIENT_SECRET = "secreteCode";
const Password = "userName";
const Username = "password";
const cognito = new CognitoIdentityServiceProvider({
region: "ap-southeast-2",
});
try {
const payload = {
UserPoolId: USER_POOL_ID,
AuthFlow: "ADMIN_NO_SRP_AUTH",
ClientId: CLIENT_ID,
AuthParameters: {
USERNAME: "username",
PASSWORD: "password",
SECRET_HASH: hashSecret(CLIENT_SECRET, Username, CLIENT_ID),
},
};
const response = await cognito.adminInitiateAuth(payload).promise();
// // console.log("respone :", response)
// console.log("before response node js lambda ::: ")
return response;
} catch (e) {
console.log("error : ", e.message);
}
}
async function test() {
return "test ";
}
exports.handler = async (event) => {
// TODO implement
console.log("event : ", event);
'
const response = {
statusCode: 200,
headers: {
"Content-Type" : "application/json",
"Access-Control-Allow-Origin" : "*",
"X-Content-Type-Option" : "nosniff",
"Content-Security-Policy" : "default-src self",
"X-frame-options" : "DENY",
"Cache-Control" : "max-age=86400",
"X-XSS-protection" : 0,
"X-rate-limit": 600,
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
},
// body: await test() // (this response is working fine
body: await isUserValid(),
};
return response;
};
Errors when tested from API gateway with proxy setting on :
{
"message": "Internal server error"
}
Response Headers
{"x-amzn-ErrorType":"InternalServerErrorException"}
I tried multiple options but nothing is working for me.
The 'body' property must be a JSON string.
await cognito.adminInitiateAuth(payload).promise() is returning an object. You need to JSON.stringify() that response. Be sure to take care of the error case , too.

How can I tell a AWS Lambda Function to redirect based off the environment?

So currently I'm using AWS Lambdas as triggers for my Cognito Passwordless authentication. For the create_auth_challenge trigger I have an AWS Lambda function that sends a link to the user to redirect them somewhere based on the environment. The only problem is that I'm not sure how to dynamically tell the function which environment the auth request is coming from.
AWS.config.update({ region: 'us-west-2' });
const SES = new AWS.SES();
exports.handler = async (event,context) => {
console.log("HERE: ", event,context);
let secretLoginCode;
if (!event.request.session || !event.request.session.length) {
// Generate a new secret login code and send it to the user
secretLoginCode = Date.now().toString().slice(-4);
try {
if ('email' in event.request.userAttributes) {
const emailResult = await SES.sendEmail({
Destination: { ToAddresses: [event.request.userAttributes.email] },
Message: {
Body: {
Html: {
Charset: 'UTF-8',
Data: `<html><body><p>This is your secret login code:</p>
<h3>Your magic link: ${INSERT ENVIRONMENT HERE}/api/auth/cognito/verify?email=${event.request.userAttributes.email}&code=${secretLoginCode}</h3></body></html>`
},
Text: {
Charset: 'UTF-8',
Data: `Your magic link: ${INSERT ENVIRONMENT HERE}/api/auth/cognito/verify?email=${event.request.userAttributes.email}&code=${secretLoginCode}`
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Your magic link'
}
},
Source: 'Company <no-reply#company.com>'
}).promise();
}
} catch (error) {
console.log(error)
}
} else {
// re-use code generated in previous challenge
const previousChallenge = event.request.session.slice(-1)[0];
secretLoginCode = previousChallenge.challengeMetadata.match(/CODE-(\d*)/)[1];
}
// Add the secret login code to the private challenge parameters
// so it can be verified by the "Verify Auth Challenge Response" trigger
event.response.privateChallengeParameters = { secretLoginCode };
// Add the secret login code to the session so it is available
// in a next invocation of the "Create Auth Challenge" trigger
event.response.challengeMetadata = `CODE-${secretLoginCode}`;
return event;
};```
This is a magic link authentication by the way.

Manually sign AppSync URL to use in Lambda gives bad signature error

In a Lambda, I would like to sign my AppSync endpoint with aws-signature-v4 in order to use it for a mutation.
The URL generated seems to be ok but it gives me the following error when I try it:
{
"errors" : [ {
"errorType" : "InvalidSignatureException",
"message" : "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. etc...
} ]
}
Here is my lambda function
import { Context, Callback } from 'aws-lambda';
import { GraphQLClient } from 'graphql-request';
const v4 = require('aws-signature-v4');
export async function handle(event: any, context: Context, callback: Callback) {
context.callbackWaitsForEmptyEventLoop = false;
const url = v4.createPresignedURL(
'POST',
'xxxxxxxxxxxxxxxxx.appsync-api.eu-west-1.amazonaws.com',
'/graphql',
'appsync',
'UNSIGNED-PAYLOAD',
{
key: 'yyyyyyyyyyyyyyyyyyyy',
secret: 'zzzzzzzzzzzzzzzzzzzzz',
region: 'eu-west-1'
}
);
const mutation = `{
FAKEviewProduct(title: "Inception") {
productId
}
}`;
const client = new GraphQLClient(url, {
headers: {
'Content-Type': 'application/graphql',
action: 'GetDataSource',
version: '2017-07-25'
}
});
try {
await client.request(mutation, { productId: 'jfsjfksldjfsdkjfsl' });
} catch (err) {
console.log(err);
callback(Error());
}
callback(null, {});
}
I got my key and secret by creating a new user and Allowing him appsync:GraphQL action.
What am I doing wrong?
This is how I trigger an AppSync mutation using by making a simple HTTP-request, using axios.
const AWS = require('aws-sdk');
const axios = require('axios');
exports.handler = async (event) => {
let result.data = await updateDb(event);
return result.data;
};
function updateDb({ owner, thingName, key }){
let req = new AWS.HttpRequest('https://xxxxxxxxxxx.appsync-api.eu-central-1.amazonaws.com/graphql', 'eu-central-1');
req.method = 'POST';
req.headers.host = 'xxxxxxxxxxx.appsync-api.eu-central-1.amazonaws.com';
req.headers['Content-Type'] = 'multipart/form-data';
req.body = JSON.stringify({
"query":"mutation ($input: UpdateUsersCamsInput!) { updateUsersCams(input: $input){ latestImage uid name } }",
"variables": {
"input": {
"uid": owner,
"name": thingName,
"latestImage": key
}
}
});
let signer = new AWS.Signers.V4(req, 'appsync', true);
signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());
return axios({
method: 'post',
url: 'https://xxxxxxxxxxx.appsync-api.eu-central-1.amazonaws.com/graphql',
data: req.body,
headers: req.headers
});
}
Make sure to give the IAM-role your Lambda function is running as, permissions for appsync:GraphQL.
Adding an answer here because I had difficulty getting the accepted answer to work and I found an issue on the AWS SDK GitHub issues that said it's not recommended to use the AWS.Signers.V4 object in production. This is how I got it to work using the popular aws4 npm module that is recommended later on in the issue linked above.
const axios = require('axios');
const aws4 = require('aws4');
const query = `
query Query {
todos {
id,
title
}
}`
const sigOptions = {
method: 'POST',
host: 'xxxxxxxxxx.appsync-api.eu-west.amazonaws.com',
region: 'eu-west-1',
path: 'graphql',
body: JSON.stringify({
query
}),
service: 'appsync'
};
const creds = {
// AWS access tokens
}
axios({
url: 'https://xxxxxxxxxx.appsync-api.eu-west/graphql',
method: 'post',
headers: aws4.sign(sigOptions, creds).headers,
data: {
query
}
}).then(res => res.data))
You don't need to construct a pre-signed URL to call an AWS AppSync endpoint. Set the authentication mode on the AppSync endpoint to AWS_IAM, grant permissions to your Lambda execution role, and then follow the steps in the "Building a JavaScript Client" tutorial to invoke a mutation or query.

How to change User Status FORCE_CHANGE_PASSWORD?

Using AWS Cognito, I want to create dummy users for testing purposes.
I then use the AWS Console to create such user, but the user has its status set to FORCE_CHANGE_PASSWORD. With that value, this user cannot be authenticated.
Is there a way to change this status?
UPDATE
Same behavior when creating user from CLI
This has finally been added to AWSCLI: https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-set-user-password.html
You can change a user's password and update status using:
aws cognito-idp admin-set-user-password \
--user-pool-id <your-user-pool-id> \
--username <username> \
--password <password> \
--permanent
Before using this, you may need to update your AWS CLI using:
pip3 install awscli --upgrade
I know it's been a while but thought this might help other people who come across this post.
You can use the AWS CLI to change the users password, however it's a multi step process:
Step 1: Get a session token for the desired user:
aws cognito-idp admin-initiate-auth --user-pool-id %USER POOL ID% --client-id %APP CLIENT ID% --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=%USERS USERNAME%,PASSWORD=%USERS CURRENT PASSWORD%
If this returns an error about Unable to verify secret hash for client, create another app client without a secret and use that client ID.
Step 2: If step 1 is successful, it will respond with the challenge NEW_PASSWORD_REQUIRED, other challenge parameters and the users session key. Then, you can run the second command to issue the challenge response:
aws cognito-idp admin-respond-to-auth-challenge --user-pool-id %USER POOL ID% --client-id %CLIENT ID% --challenge-name NEW_PASSWORD_REQUIRED --challenge-responses NEW_PASSWORD=%DESIRED PASSWORD%,USERNAME=%USERS USERNAME% --session %SESSION KEY FROM PREVIOUS COMMAND with ""%
If you get an error about Invalid attributes given, XXX is missing pass the missing attributes using the format userAttributes.$FIELD_NAME=$VALUE
The above command should return a valid Authentication Result and appropriate Tokens.
Important: For this to work, the Cognito User Pool MUST have an App client configured with ADMIN_NO_SRP_AUTH functionality (Step 5 in this doc).
Just add this code after your onSuccess: function (result) { ... }, within your login function. Your user will then have status CONFIRMED.
newPasswordRequired: function(userAttributes, requiredAttributes) {
// User was signed up by an admin and must provide new
// password and required attributes, if any, to complete
// authentication.
// the api doesn't accept this field back
delete userAttributes.email_verified;
// unsure about this field, but I don't send this back
delete userAttributes.phone_number_verified;
// Get these details and call
cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, this);
}
You can change that user status FORCE_CHANGE_PASSWORD by calling respondToAuthChallenge() on the user like this:
var params = {
ChallengeName: 'NEW_PASSWORD_REQUIRED',
ClientId: 'your_own3j6...0obh',
ChallengeResponses: {
USERNAME: 'user3',
NEW_PASSWORD: 'changed12345'
},
Session: 'xxxxxxxxxxZDMcRu-5u...sCvrmZb6tHY'
};
cognitoidentityserviceprovider.respondToAuthChallenge(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
After this, you'll see in the console that user3 status is CONFIRMED.
Sorry you are having difficulties. We do not have a one step process where you can just create users and authenticate them directly. We might change this in the future such as to allow administrators to set passwords that are directly usable by users. For now, when you create users either using AdminCreateUser or by signing up users with the app, extra steps are required, either forcing users to change the password upon login or having users verify the email or phone number to change the status of the user to CONFIRMED.
not sure if you are still fighting with this but for creating a bunch of test users only, I used the awscli as such:
Use the sign-up subcommand from cognito-idp to create the user
aws cognito-idp sign-up \
--region %aws_project_region% \
--client-id %aws_user_pools_web_client_id% \
--username %email_address% \
--password %password% \
--user-attributes Name=email,Value=%email_address%
Confirm the user using admin-confirm-sign-up
aws cognito-idp admin-confirm-sign-up \
--user-pool-id %aws_user_pools_web_client_id% \
--username %email_address%
UPDATE:
There have been some updates, and Amplify client is no longer needed.
After adminCreateUser(), you can now just use
cisp.adminSetUserPassword({
UserPoolId: pool_id,
Username: login,
Password: password,
Permanent: true
})
[https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html]
this will set the user to "confirmed".
UPDATE:
I am now using this, translated to amplify, inside a NodeJS Lambda:
// enable node-fetch polyfill for Node.js
global.fetch = require("node-fetch").default;
global.navigator = {};
const AWS = require("aws-sdk");
const cisp = new AWS.CognitoIdentityServiceProvider();
const Amplify = require("#aws-amplify/core").default;
const Auth = require("#aws-amplify/auth").default;
...
/*
this_user: {
given_name: string,
password: string,
email: string,
cell: string
}
*/
const create_cognito = (this_user) => {
let this_defaults = {
password_temp: Math.random().toString(36).slice(-8),
password: this_user.password,
region: global._env === "prod" ? production_region : development_region,
UserPoolId:
global._env === "prod"
? production_user_pool
: development_user_pool,
ClientId:
global._env === "prod"
? production_client_id
: development_client_id,
given_name: this_user.given_name,
email: this_user.email,
cell: this_user.cell,
};
// configure Amplify
Amplify.configure({
Auth: {
region: this_defaults.region,
userPoolId: this_defaults.UserPoolId,
userPoolWebClientId: this_defaults.ClientId,
},
});
if (!Auth.configure())
return Promise.reject("could not configure amplify");
return new Promise((resolve, reject) => {
let _result = {};
let this_account = undefined;
let this_account_details = undefined;
// create cognito account
cisp
.adminCreateUser({
UserPoolId: this_defaults.UserPoolId,
Username: this_defaults.given_name,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: this_defaults.password_temp,
UserAttributes: [
{ Name: "given_name", Value: this_defaults.given_name },
{ Name: "email", Value: this_defaults.email },
{ Name: "phone_number", Value: this_defaults.cell },
{ Name: "email_verified", Value: "true" },
],
})
.promise()
.then((user) => {
console.warn(".. create_cognito: create..");
_result.username = user.User.Username;
_result.temporaryPassword = this_defaults.password_temp;
_result.password = this_defaults.password;
// sign into cognito account
return Auth.signIn(_result.username, _result.temporaryPassword);
})
.then((user) => {
console.warn(".. create_cognito: signin..");
// complete challenge
return Auth.completeNewPassword(user, _result.password, {
email: this_defaults.email,
phone_number: this_defaults.cell,
});
})
.then((user) => {
console.warn(".. create_cognito: confirmed..");
this_account = user;
// get details
return Auth.currentAuthenticatedUser();
})
.then((this_details) => {
if (!(this_details && this_details.attributes))
throw "account creation failes";
this_account_details = Object.assign({}, this_details.attributes);
// signout
return this_account.signOut();
})
.then(() => {
console.warn(".. create_cognito: complete");
resolve(this_account_details);
})
.catch((err) => {
console.error(".. create_cognito: error");
console.error(err);
reject(err);
});
});
};
I am setting a temp password and then later resetting it to the user's requested password.
OLD POST:
You can solve this using the amazon-cognito-identity-js SDK by authenticating with the temporary password after the account creation with cognitoidentityserviceprovider.adminCreateUser(), and running cognitoUser.completeNewPasswordChallenge() within cognitoUser.authenticateUser( ,{newPasswordRequired}) - all inside the function that creates your user.
I am using the below code inside AWS lambda to create enabled Cognito user accounts. I am sure it can be optimized, be patient with me. This is my first post, and I am still pretty new to JavaScript.
var AWS = require("aws-sdk");
var AWSCognito = require("amazon-cognito-identity-js");
var params = {
UserPoolId: your_poolId,
Username: your_username,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: your_temporaryPassword,
UserAttributes: [
{ Name: "given_name", Value: your_given_name },
{ Name: "email", Value: your_email },
{ Name: "phone_number", Value: your_phone_number },
{ Name: "email_verified", Value: "true" }
]
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
let promise = new Promise((resolve, reject) => {
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
promise
.then(data => {
// login as new user and completeNewPasswordChallenge
var anotherPromise = new Promise((resolve, reject) => {
var authenticationDetails = new AWSCognito.AuthenticationDetails({
Username: your_username,
Password: your_temporaryPassword
});
var poolData = {
UserPoolId: your_poolId,
ClientId: your_clientId
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username: your_username,
Pool: userPool
};
var cognitoUser = new AWSCognito.CognitoUser(userData);
let finalPromise = new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(authResult) {
cognitoUser.getSession(function(err) {
if (err) {
} else {
cognitoUser.getUserAttributes(function(
err,
attResult
) {
if (err) {
} else {
resolve(authResult);
}
});
}
});
},
onFailure: function(err) {
reject(err);
},
newPasswordRequired(userAttributes, []) {
delete userAttributes.email_verified;
cognitoUser.completeNewPasswordChallenge(
your_newPoassword,
userAttributes,
this
);
}
});
});
finalPromise
.then(finalResult => {
// signout
cognitoUser.signOut();
// further action, e.g. email to new user
resolve(finalResult);
})
.catch(err => {
reject(err);
});
});
return anotherPromise;
})
.then(() => {
resolve(finalResult);
})
.catch(err => {
reject({ statusCode: 406, error: err });
});
If you are trying to change status as a admin from the console. Then follow the below steps after creating the user.
In Cognito goto -> "manage user pool" ->
Goto "App client settings" under App integration section.
Check on the below items
i) Cognito User Pool ii) Authorization code grant iii) Implicit grant iv) phone v) email vi) openid vii) aws.cognito.signin.user.admin viii) profile
Enter the callback url of your application. If you are not sure enter for example: https://google.com and later you can change it to your actual callback url
click on save changes.
Once changes are saved click on the link "Launch Hosted UI"
Enter the credentials of the new created user
Reset the password with new credentials and share the same to the user
step 2
step 3 4 5 6
step 7
step 8
For Java SDK, assuming your Cognito client is setup and you have your user in the FORCE_CHANGE_PASSWORD state you can do the following to get your user CONFIRMED... and then auth'd as normal.
AdminCreateUserResult createUserResult = COGNITO_CLIENT.adminCreateUser(createUserRequest());
AdminInitiateAuthResult authResult = COGNITO_CLIENT.adminInitiateAuth(authUserRequest());
Map<String,String> challengeResponses = new HashMap<>();
challengeResponses.put("USERNAME", USERNAME);
challengeResponses.put("NEW_PASSWORD", PASSWORD);
RespondToAuthChallengeRequest respondToAuthChallengeRequest = new RespondToAuthChallengeRequest()
.withChallengeName("NEW_PASSWORD_REQUIRED")
.withClientId(CLIENT_ID)
.withChallengeResponses(challengeResponses)
.withSession(authResult.getSession());
COGNITO_CLIENT.respondToAuthChallenge(respondToAuthChallengeRequest);
Hope it helps with those integration tests (Sorry about the formatting)
Basically this is the same answer but for .Net C# SDK:
The following will make a full admin user creation with desired username and password.
Having the following User model:
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
You can create a user and make it ready to use using:
public void AddUser(User user)
{
var tempPassword = "ANY";
var request = new AdminCreateUserRequest()
{
Username = user.Username,
UserPoolId = "MyuserPoolId",
TemporaryPassword = tempPassword
};
var result = _cognitoClient.AdminCreateUserAsync(request).Result;
var authResponse = _cognitoClient.AdminInitiateAuthAsync(new AdminInitiateAuthRequest()
{
UserPoolId = "MyuserPoolId",
ClientId = "MyClientId",
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
AuthParameters = new Dictionary<string, string>()
{
{"USERNAME",user.Username },
{"PASSWORD", tempPassword}
}
}).Result;
_cognitoClient.RespondToAuthChallengeAsync(new RespondToAuthChallengeRequest()
{
ClientId = "MyClientId",
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
ChallengeResponses = new Dictionary<string, string>()
{
{"USERNAME",user.Username },
{"NEW_PASSWORD",user.Password }
},
Session = authResponse.Session
});
}
OK. I finally have code where an administrator can create a new user. The process goes like this:
Admin creates the user
User receives an email with their temporary password
User logs in and is asked to change their password
Step 1 is the hard part. Here's my code for creating a user in Node JS:
let params = {
UserPoolId: "#cognito_pool_id#",
Username: username,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
UserAttributes: [
{ Name: "given_name", Value: firstName },
{ Name: "family_name", Value: lastName},
{ Name: "name", Value: firstName + " " + lastName},
{ Name: "email", Value: email},
{ Name: "custom:title", Value: title},
{ Name: "custom:company", Value: company + ""}
],
};
let cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
cognitoIdentityServiceProvider.adminCreateUser(params, function(error, data) {
if (error) {
console.log("Error adding user to cognito: " + error, error.stack);
reject(error);
} else {
// Uncomment for interesting but verbose logging...
//console.log("Received back from cognito: " + CommonUtils.stringify(data));
cognitoIdentityServiceProvider.adminUpdateUserAttributes({
UserAttributes: [{
Name: "email_verified",
Value: "true"
}],
UserPoolId: "#cognito_pool_id#",
Username: username
}, function(err) {
if (err) {
console.log(err, err.stack);
} else {
console.log("Success!");
resolve(data);
}
});
}
});
Basically, you need to send a second command to force the email to be considered verified. The user still needs to go to their email to get the temporary password (which also verifies the email). But without that second call that sets the email to verified, you won't get the right call back to reset their password.
I know It is the same answer, but thought it might help Go developer community. basically it is initiating auth request, get the session and respond to the challenge NEW_PASSWORD_REQUIRED
func sessionWithDefaultRegion(region string) *session.Session {
sess := Session.Copy()
if v := aws.StringValue(sess.Config.Region); len(v) == 0 {
sess.Config.Region = aws.String(region)
}
return sess
}
func (c *CognitoAppClient) ChangePassword(userName, currentPassword, newPassword string) error {
sess := sessionWithDefaultRegion(c.Region)
svc := cognitoidentityprovider.New(sess)
auth, err := svc.AdminInitiateAuth(&cognitoidentityprovider.AdminInitiateAuthInput{
UserPoolId:aws.String(c.UserPoolID),
ClientId:aws.String(c.ClientID),
AuthFlow:aws.String("ADMIN_NO_SRP_AUTH"),
AuthParameters: map[string]*string{
"USERNAME": aws.String(userName),
"PASSWORD": aws.String(currentPassword),
},
})
if err != nil {
return err
}
request := &cognitoidentityprovider.AdminRespondToAuthChallengeInput{
ChallengeName: aws.String("NEW_PASSWORD_REQUIRED"),
ClientId:aws.String(c.ClientID),
UserPoolId: aws.String(c.UserPoolID),
ChallengeResponses:map[string]*string{
"USERNAME":aws.String(userName),
"NEW_PASSWORD": aws.String(newPassword),
},
Session:auth.Session,
}
_, err = svc.AdminRespondToAuthChallenge(request)
return err
}
Here's a unit test:
import (
"fmt"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestCognitoAppClient_ChangePassword(t *testing.T) {
Convey("Testing ChangePassword!", t, func() {
err := client.ChangePassword("user_name_here", "current_pass", "new_pass")
Convey("Testing ChangePassword Results!", func() {
So(err, ShouldBeNil)
})
})
}
I have been many times in the same situation. So wrote small CLI in golang to exactly either auth as user ( for further testing purposes ) or just administratively reset the pass.
Then all what you run as command is
$ > go-cognito-authy --profile cloudy -region eu-central-1 admin reset-pass --username rafpe --pass-new 'Password.0ne2!' --clientID 2jxxxiuui123 --userPoolID eu-central-1_CWNnTiR0j --session "bCqSkLeoJR_ys...."
Solution is available on github https://github.com/RafPe/go-cognito-authy/tree/master
You can also just use the Hosted UI of Cognito in case you have one for your application. Just login with the desired user and you will be prompted to change your password. After that the users status is confirmed and you can proceed as normal.