如何将Amplify Cognito会话从本地响应传递到Webview?

时间:2019-10-23 23:07:11

标签: react-native webview amazon-cognito aws-amplify

我有一个React Native应用,可呈现Web应用的WebView

react本机应用程序使用Cognito和Amplify进行身份验证。 该Web应用程序还使用相同的Cognito和Amplify进行身份验证。

我有一个在react native中内置的登录流程,该流程具有电子邮件/密码登录和社交媒体联合Oauth登录。这两个登录流都可以在react native空间中成功工作并返回一个

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

当react native应用程序呈现WebView时,该Web应用程序未经身份验证。我能够将CognitoUserSession数据成功传递到WebView中。不幸的是,我没有办法让Amplify对此会话进行重新认证。

1 个答案:

答案 0 :(得分:0)

这是我编写的有效的mobileLogin函数

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}`);
}
 };
}