aws-samples/amazon-cognito-passwordless-email-auth

How to persist custom challenge session

agostbiro opened this issue · 6 comments

Hi,

I'm wondering what's the best solution to persisting the authentication challenge session across page loads. Consider the following scenario:

  1. User goes to /login and requests login code
  2. User retrieves login code from email
  3. User reloads /login (or opens it in new tab)

The auth challenge session information is now lost and no info is stored by aws-amplify in local storage since the user is not authenticated yet.

That is not a trivial problem. A trick I've used is to store the session in Local Storage.

// Store session:
const session = (cognitoUser as any).Session;
localStorage.setItem('session', session);
localStorage.setItem('username', email);

// Then in another tab:
// Retrieve the stored session, and create the CognitoUser again, assigning the session:
const username = localStorage.getItem('username');
const session = localStorage.getItem('session');
const cognitoUser = new CognitoUser({ Username: username, Pool: userPool });
(cognitoUser as any).Session = session;

// Now you can continue the auth flow as you would before

That works across tabs--but not across browsers.

A cross browser solution would be more elaborate and would need to utilize storage elsewhere, where both browsers can access it.

Thanks! Same browser fits my requirements.

I've improved the persistence method a bit and posted a full snippet on SO:

https://stackoverflow.com/a/59613024/2650622

@ottokruse How do you get userPool when creating a new CognitoUser ?

Can be instantiated like this:

import { CognitoUserPool } from 'amazon-cognito-identity-js';
new CognitoUserPool({
    ClientId: environment.cognitoAppClientId,
    UserPoolId: environment.cognitoUserPoolId,
});

environment in my case Angular environment file