如何将 Amplify Cognito 会话从本机反应传递到 webview?

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

我有一个反应本机应用程序呈现 Web 应用程序的 WebView

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

我在本机反应中构建了一个登录流程,该流程具有 email/password 登录和社交媒体联合 Oauth 登录。这两个登录流程都在 react native space 和 return a

中成功运行
CognitoUserSession {
  idToken: CognitoIdToken, 
  refreshToken: CognitoRefreshToken, 
  accessToken: CognitoAccessToken, 
  clockDrift: 0
}

当本机应用程序呈现 WebView 时,网络应用程序未经身份验证。我能够成功地将 CognitoUserSession 数据传递到 WebView 中。不幸的是,我没有看到让 Amplify 重新验证此会话的方法。

这是我写的 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}`);
}
 };
}

对于仍然需要它的人。

首先,您需要将 oauth 设置添加到 Web 应用程序的 AwsExports.json。

const AwsExports = {
  Auth: {
    ...
    oauth: {
      domain: 'xxx.auth.us-east-1.amazoncognito.com',
      scope:['openid'],
      redirectSignIn: 'https://example.com',
      redirectSignOut: 'https://example.com',
      responseType: 'token'
    }
  },
};

然后你可以用uri传递令牌。

const session      = await Auth.currentSession(),
      id_token     = session.getIdToken().getJwtToken(),
      access_token = session.getAccessToken().getJwtToken(),
      uri          = `https://example.com##id_token=${id_token}&access_token=${access_token}`;

您实际上应该设置 oauth 东西。 因为 webview 作为 Oauth 流程的一部分打开,所以可以执行 oauth loggin out 流程。 所以如果没有正确设置 oauth,就会出现错误