Search code examples
react-nativewebviewamazon-cognitoaws-amplify

How to pass an Amplify Cognito session from react native to webview?


I have a react native app that renders a WebView of a Web app

The react native app uses Cognito and Amplify for authentication. The web app also uses the same Cognito and Amplify for authentication.

I have a login flow built with in the react native that has email/password login and social media federated Oauth logins. Both these login flows successfully work in the react native space and return a

CognitoUserSession {
  idToken: CognitoIdToken, 
  refreshToken: CognitoRefreshToken, 
  accessToken: CognitoAccessToken, 
  clockDrift: 0
}

When the react native app renders the WebView the web app is unauthenticated. I am able to pass the CognitoUserSession data into the WebView successfully. Unfortunately, I don't see a way to have Amplify re-authenticate with this session.


Solution

  • this is the mobileLogin function I wrote that works

    import Amplify, { Auth } from 'aws-amplify';
    import {
      CognitoUser,
      CognitoUserSession,
      CognitoIdToken,
      CognitoRefreshToken,
      CognitoAccessToken,
    } from 'amazon-cognito-identity-js';
    
    window.mobileLogin = async function(mobileSession) {
      amplify = Amplify.configure({
        ...config().amplify,
        userPoolWebClientId: '', //switch to mobile client
      });
    
    const localSession = new CognitoUserSession({
      IdToken: new CognitoIdToken({ IdToken: mobileSession.idToken.jwtToken }),
      RefreshToken: new CognitoRefreshToken({ RefreshToken: mobileSession.refreshToken }),
      AccessToken: new CognitoAccessToken({ AccessToken: mobileSession.accessToken.jwtToken }),
    });
    
    const localUser = new CognitoUser({
      Username: mobileSession.accessToken.payload.username,
      Pool: Auth.userPool,
      Storage: Auth.userPool.storage,
    });
    localUser.setSignInUserSession(localSession);
    
    // this seems like a hack
    Auth.currentCredentials = async () => localSession;
    
    try {
      await Auth.currentSession();
      console.warn(`mobile login current session!!`);
      store.dispatch(silentReloginAction())
    } catch (ex) {
      console.warn(`mobile login ${ex}`);
    }
     };
    }