Skip to content

Instantly share code, notes, and snippets.

@jatazoulja
Last active February 12, 2018 07:32
Show Gist options
  • Save jatazoulja/a0cfcf23cf8a55e5306e1ebda58f680e to your computer and use it in GitHub Desktop.
Save jatazoulja/a0cfcf23cf8a55e5306e1ebda58f680e to your computer and use it in GitHub Desktop.
NOTE: this uses AWS USER POOL custom UI. Please configure your user pool first.
/**
* NOTE: this uses aws USER POOL custom UI.
* Please configure your user pool first.
*/
export async function facebookOAuth2() {
return new Promise((resolve, reject) => {
let authHost = 'https://<sub domain>.auth.ap-southeast-1.amazoncognito.com';
let identityProvider = 'Facebook';
let redirectUri = 'http://localhost:3000/oauth/';
let responseType = 'token';
let clientId = config.cognito.APP_CLIENT_ID;
let state = 'some_state';
let scope = 'profile email openid';
let authUrl = `${authHost}/oauth2/authorize?identity_provider=${identityProvider}&redirect_uri=${redirectUri}&response_type=${responseType}&client_id=${clientId}&state=${state}&scope=${scope}`
console.debug(authUrl);
window.open(
authUrl,
"facebook",
"location,toolbar,resizable,scrollbars,status,width=600,height=600"
);
window.addEventListener("message", res => {
let tokensData = res.data;
let token = tokensData.IdToken;
let payload = token.split('.')[1];
payload = JSON.parse(atob(payload));
let username = payload['cognito:username'];
const cognitoIdentityService = new AWS.CognitoIdentityServiceProvider()
let userPoolId = config.cognito.USER_POOL_ID;
let clientId = config.cognito.APP_CLIENT_ID;
let login = 'cognito-idp.' + config.REGION + '.amazonaws.com/' + userPoolId;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: config.cognito.IDENTITY_POOL_ID,
Logins: {
[login]: token
}
});
AWS.config.update({ region: config.apiGateway.REGION });
// AWS.config.credentials.params.Logins['cognito-idp.' + config.REGION + '.amazonaws.com/' + userPoolId] = token;
AWS.config.credentials.get(err => {
if (err) {
return reject(err);
}
let poolData = {
UserPoolId: userPoolId, // Your user pool id here
ClientId: clientId // Your client id here
};
let userPool = new CognitoUserPool(poolData);
let userData = {
Username: username,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
cognitoUser.signInUserSession = cognitoUser.getCognitoUserSession(tokensData);
cognitoUser.cacheTokens();
console.log("Amazon Cognito Identity", AWS.config.credentials.identityId);
resolve(AWS.config.credentials.identityId);
});
}, false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment