I have one cognito user pool that is used by multiple applications. I have a central auth application where users can login/signup/resetPasswords/etc anything auth related.
I have five other application that users can access. Rather than having them log into each application I embed the auth application into an iframe. If the user is logged in it does a postMessage to the parent document, or if the token is not valid once the user logs in, it will do a postMessage with the cognito session object.
Is there something such as Auth.setUserSession(session) that can be done in the parent document? Right now I am having to build a bunch of strings with token and username values and saving them manually to localStorage.
I've been looking through the aws-amplify auth code, but I don't see anything that can accomplish this.
Thanks.
In the parent document:
const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
const eventListener = window[eventMethod];
const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';
eventListener(messageEvent, async evt => {
const session = _.get(evt, 'data.session');
if (session) {
this.saveUserSession(session);
}
}, false);
private saveUserSession(session) {
// this is the code that I would like to simplify with something
// Auth.setUserSession(session)
const cognitoClientId = environment.COGNITO.Auth.userPoolWebClientId;
const userName = _.get(session, 'idToken.payload.email', '');
const makeKey = (name) => `CognitoIdentityServiceProvider.${cognitoClientId}.${userName}.${name}`;
localStorage.setItem(makeKey('accessToken'), JSON.stringify(_.get(session, 'accessToken', '')));
localStorage.setItem(makeKey('idToken'), JSON.stringify(_.get(session, 'idToken', '')));
localStorage.setItem(makeKey('refreshToken'), JSON.stringify(_.get(session, 'refreshToken', '')));
localStorage.setItem(makeKey('clockDrift'), JSON.stringify(_.get(session, 'clockDrift', '')));
localStorage.setItem(`CognitoIdentityServiceProvider.${cognitoClientId}.LastAuthUser`, userName);
}
In the auth application, after a user successfully logs in:
const session = await Auth.currentSession();
window.parent.postMessage({session}, '*');