Skip to content

Instantly share code, notes, and snippets.

@sbussard
Created December 30, 2016 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sbussard/7344c6e1f56051da0758d1403a4343b1 to your computer and use it in GitHub Desktop.
Save sbussard/7344c6e1f56051da0758d1403a4343b1 to your computer and use it in GitHub Desktop.
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
Copy link
Author

sbussard commented Dec 30, 2016

proof of concept, not proof from bullets

@sbussard
Copy link
Author

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