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

如何在React Native中使用AWS Amplify实现用户持久登录

Got it, let's figure out how to keep your users logged in even after closing your React Native app with AWS Cognito. Here's a step-by-step breakdown tailored to your code:

1. First, Ensure Persistent Storage is Configured

AWS Amplify (which you're likely using with Cognito) needs a local storage solution to save user session data. For React Native, we use @react-native-async-storage/async-storage—it keeps data intact even when the app closes.

  • Install the dependency if you haven't already:
    npm install @react-native-async-storage/async-storage
    # Or with yarn: yarn add @react-native-async-storage/async-storage
    
  • Update your Amplify initialization to use this storage:
    import Amplify from 'aws-amplify';
    import config from './aws-exports';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    Amplify.configure({
      ...config,
      storage: AsyncStorage, // Tell Amplify to use AsyncStorage for session persistence
    });
    

2. Add Auto-Login Check on App Startup

Your current code only sets isAuthenticated to false initially. We need to check if there's an existing valid session when the component mounts, and update the state accordingly.

Modify your component to add this check:

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Auth } from 'aws-amplify';
import Tabs from './Tabs';

class App extends Component {
  state = { isAuthenticated: false }

  authenticate = (isAuthenticated) => {
    this.setState({ isAuthenticated });
  }

  // Check for existing authenticated session
  checkAuthStatus = async () => {
    try {
      // `bypassCache: false` prioritizes local stored data first
      const user = await Auth.currentAuthenticatedUser({ bypassCache: false });
      console.log('Current logged-in user:', user);
      this.authenticate(true);
    } catch (err) {
      console.log('No active session found:', err);
      this.authenticate(false);
    }
  }

  // Run the check when the component loads
  componentDidMount() {
    this.checkAuthStatus();
  }

  render() {
    if (this.state.isAuthenticated) {
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Hello {Auth.user.username}!</Text>
        </View>
      );
    }
    return (
      <View style={styles.container}>
        <Tabs screenProps={{ authenticate: this.authenticate }} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

export default App;

3. Verify Cognito User Pool Settings

Double-check your Cognito configuration to ensure refresh tokens are enabled (they let Amplify automatically renew sessions):

  • Go to your AWS Cognito User Pool → App clients
  • Select your app client, then scroll to Refresh token expiration—set a reasonable window (e.g., 30 days)
  • Ensure the Allowed auth flows includes USER_PASSWORD_AUTH (if you're using username/password login) or the appropriate flow for your setup.

How This Works

When a user logs in successfully, Amplify automatically saves their session tokens (access, ID, refresh) to AsyncStorage. On app startup, checkAuthStatus calls Auth.currentAuthenticatedUser() which checks this local storage:

  • If a valid session exists (or can be refreshed with the refresh token), it sets isAuthenticated to true
  • If no session is found or it's expired, it falls back to the login screen

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:00:36