Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
how to authenticate an aws cognito user in the browser
import AWS from 'aws-sdk/global';
import S3 from 'aws-sdk/clients/s3';
import {
AuthenticationDetails,
CognitoUser,
CognitoUserPool,
} from 'amazon-cognito-identity-js';
const REGION = 'some-string-value';
const USER_POOL_ID = 'some-string-value';
const IDENTITY_POOL_ID = 'some-string-value';
const APP_CLIENT_ID = 'some-string-value';
const POOL_KEY = `cognito-idp.${REGION}.amazonaws.com/${USER_POOL_ID}`;
let Username = 'some-string-value';
let Password = 'some-string-value';
let authenticationDetails = new AuthenticationDetails({
Username,
Password
});
let userPool = new CognitoUserPool({
UserPoolId: USER_POOL_ID,
ClientId: APP_CLIENT_ID
});
let cognitoUser = new CognitoUser({
Username,
Pool: userPool
});
let skateboards = {
mfaRequired(codeDeliveryDetails) {
let mfaCode = prompt('MFA code is required!');
cognitoUser.sendMFACode(mfaCode, mfaRequired);
},
newPasswordRequired(userAttributes, requiredAttributes) {
delete userAttributes.email_verified; // it's returned but not valid to submit
let newPassword = prompt('A new password is required!');
cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes, newPasswordRequired);
}
};
let updateAWSCreds = (jwtToken) => {
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: IDENTITY_POOL_ID,
Logins: {
[POOL_KEY]: jwtToken
}
});
};
let authenticateCognitoUser = async ({mfaRequired, newPasswordRequired} = skateboards) => {
return new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess(result) {
let jwtToken = result.getIdToken().getJwtToken();
updateAWSCreds(jwtToken);
resolve();
},
onFailure(err) {
reject(err);
},
mfaRequired,
newPasswordRequired
});
});
};
let doSomethingInS3ForExample = async () => {
await authenticateCognitoUser();
// now do your stuff
};
doSomethingInS3ForExample();
@sbussard

This comment has been minimized.

Copy link
Owner Author

commented Dec 30, 2016

proof of concept, not proof from bullets

@sbussard

This comment has been minimized.

Copy link
Owner Author

commented Dec 30, 2016

lines 68 and 69 don't resolve the promise. That's bad. I'll update it if I get a chance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.