You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过现有Cognito池实现RN到Web应用的身份认证?

跨端身份认证解决方案(React Native → Next.js + Cognito)

核心思路

不要直接通过URL传递JWT或用户对象(存在泄露风险),采用Cognito官方推荐的授权码流程+PKCE实现安全跨端认证。RN与Web共享同一用户池,利用RN已登录状态通过授权码交换获取Web端会话,自动维持登录状态。

实现步骤

1. React Native端:构造安全跳转链接

使用react-native-inappbrowser-reborn打开Web的Cognito授权页面,Amplify会自动生成PKCE参数(防止授权码被劫持),同时带上自定义标识isMobileBrowser和目标回调地址:

import InAppBrowser from 'react-native-inappbrowser-reborn';
import { Auth, AuthConfig } from 'aws-amplify';

const openWebDashboard = async () => {
  // 确保RN用户已登录
  await Auth.currentAuthenticatedUser();
  
  // 从Amplify配置中获取用户池信息
  const authConfig = Auth.configure() as AuthConfig;
  const clientId = authConfig.userPoolWebClientId!;
  const userPoolDomain = authConfig.userPoolDomain!;
  const redirectUri = 'https://your-web-app.com/dashboard'; // Web端Dashboard地址

  // 构造Cognito授权URL
  const authUrl = `${userPoolDomain}/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=openid+email+profile&isMobileBrowser=true`;

  if (await InAppBrowser.isAvailable()) {
    await InAppBrowser.openAuth(authUrl, redirectUri, {
      showTitle: false,
      enableUrlBarHiding: true,
    });
  } else {
    // 降级到系统浏览器
    Linking.openURL(authUrl);
  }
};

2. Next.js端:处理移动端认证请求

在Dashboard页面挂载时,检查URL中的Cognito授权码和isMobileBrowser标识,完成认证并维持会话:

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { Auth } from 'aws-amplify';
import Authenticated from '../components/Authenticated';
import Dashboard from '../components/Dashboard';

const DashboardPage = () => {
  const { query, push } = useRouter();

  useEffect(() => {
    const handleMobileAuth = async () => {
      // 校验移动端请求及Cognito授权码
      if (query?.isMobileBrowser && query?.code) {
        try {
          // Amplify自动完成授权码交换Token,并将会话存入Cookie/LocalStorage
          await Auth.federatedSignIn({ provider: 'COGNITO' });
          // 清除URL中的认证参数,优化页面体验
          await push('/dashboard', undefined, { shallow: true });
        } catch (err) {
          console.error('移动端认证失败:', err);
          await push('/login');
        }
      } else {
        // 非移动端请求,常规校验会话状态
        try {
          await Auth.currentAuthenticatedUser({ bypassCache: true });
        } catch {
          await push('/login');
        }
      }
    };

    handleMobileAuth();
  }, [query, push]);

  return (
    <Authenticated>
      <Dashboard />
    </Authenticated>
  );
};

export default DashboardPage;

3. 会话维持说明

  • Amplify在Web端默认将认证Token存入HttpOnly Cookie,移动浏览器会自动维护该Cookie,只要用户不清除浏览器数据,下次打开Web应用时Amplify会自动读取Cookie恢复会话。
  • 无需手动管理Token,Amplify会在API请求(如Apollo)中自动注入认证头。

关键配置注意事项

  • 确保Web与RN的Amplify配置完全一致:userPoolId、userPoolWebClientId、userPoolDomain必须相同。
  • 在Cognito用户池的App客户端设置中,将Web端的redirect_uri(如https://your-web-app.com/dashboard)添加到允许的回调URL列表。

内容的提问来源于stack exchange,提问作者IncognitoUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:15:59