Created
December 30, 2016 18:09
-
-
Save sbussard/7344c6e1f56051da0758d1403a4343b1 to your computer and use it in GitHub Desktop.
how to authenticate an aws cognito user in the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
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
proof of concept, not proof from bullets