aws 集成

    科技2025-03-15  25

    aws 集成

    Originally published at https://www.instamobile.io on August 29, 2020.

    最初于 2020年8月29日 在 https://www.instamobile.io 上 发布 。

    This tutorial is going to take a look at one of the most important features of a mobile application — the authentication. You know the scenario. You need to store some amount of user information (credentials) for them to get back and re-use the application rather than creating a new account.

    本教程将介绍移动应用程序最重要的功能之一-身份验证。 您知道这种情况。 您需要存储一些用户信息(凭证),以便他们取回并重新使用应用程序,而不是创建新帐户。

    Please make sure to have an AWS account before you begin this tutorial. If you don’t, please sign up for one.

    在开始本教程之前,请确保具有一个AWS账户。 如果您不这样做, 请注册一个。

    什么是AWS Amplify? (What is AWS Amplify?)

    Amazon Web Service is a technology that provides cloud services. Since its launch in 2017, Amplify has come a long way in terms of providing a set of services in the form of the toolchain. It is also open source.

    Amazon Web Service是一种提供云服务的技术。 自2017年推出以来,Amplify在以工具链形式提供一系列服务方面已经走了很长一段路。 它也是开源的。

    To build authentication into a React Native and Expo application with Amplify you first need to install the AWS Amplify CLI. Open a terminal window and execute the command below to install the CLI. We are going to install it as a global module.

    要使用Amplify将身份验证构建到React Native和Expo应用程序中,您首先需要安装AWS Amplify CLI。 打开一个终端窗口,执行以下命令以安装CLI。 我们将其安装为全局模块。

    npm install -g @aws-amplify/cli

    Using Amplify’s CLI tool you are going to find several really helpful CLI plugins and services that you can enable with one click when integrating with a framework like React Native. Services such as GraphQL and REST APIs, authentication UI as well as backend support, storage, hosting, and many more are made available by Amplify’s CLI.

    使用Amplify的CLI工具,您将找到几个非常有用的CLI插件和服务,在与React Native等框架集成时,只需单击一下即可启用。 Amplify的CLI可提供诸如GraphQL和REST API,身份验证UI以及后端支持,存储,托管等服务,以及更多其他服务。

    React Native和AWS Amplify入门 (Getting Started with React Native and AWS Amplify)

    Start by creating a new application project. We are going to Expo CLI to generate the project. Open a terminal window and create a new React Native app.

    首先创建一个新的应用程序项目。 我们将使用Expo CLI生成项目。 打开一个终端窗口并创建一个新的React Native应用程序。

    npx expo-cli init expo-amplify-example

    This command creates a new directory called expo-amplify-example. You can name it whatever you want. Inside this directory, you are going to find a complete React Native + Expo SDK project generated. Please note that, on running the above command, you'll be asked by the CLI which template to use. This tutorial uses a blank template from the managed workflow. If you are familiar with any other template, feel free to choose that.

    此命令创建一个名为expo-amplify-example的新目录。 您可以随意命名。 在此目录中,您将找到一个完整的React Native + Expo SDK项目。 请注意,在运行上述命令时,CLI会询问您要使用哪个模板。 本教程使用托管工作流程中的blank模板。 如果您熟悉其他模板,请随意选择。

    Expo CLI is a command-line utility to create React Native apps with no build configuration. The reason we’re relying on it is that, first, it’s an awesome tool for such use cases.

    Expo CLI是一个命令行实用程序,用于创建没有构建配置的React Native应用程序。 我们依赖它的原因是,首先,它是用于此类用例的出色工具。

    创建一个新的AWS IAM用户 (Create a New AWS IAM User)

    Once signed in the AWS account, run the below command from a terminal window. This command asks you to sign in to the AWS Console.

    登录AWS账户后,从终端窗口运行以下命令。 此命令要求您登录AWS控制台。

    amplify configure

    This opens up the AWS console dashboard. Go back to the terminal and press the enter key to continue. This leads you through a bunch of questions in order to configure a user account to use Amplify with the React Native application.

    这将打开AWS控制台仪表板。 返回终端,然后按Enter键继续。 这将引导您解决一系列问题,以便配置用户帐户以将Amplify与React Native应用程序一起使用。

    Choose a region: us-east-2

    选择地区 :us-east-2

    Specify the username of the new IAM user: expo-amplify

    指定新的IAM用户的用户名 :expo-amplify

    On entering the username, press enter and the AWS console opens again in a browser window for you to add a user.

    输入用户名后,按Enter键,AWS控制台将在浏览器窗口中再次打开,供您添加用户。

    In the above screen, make sure that Programmatic accessis checked. It allows the new user to have access to create resources in the form of different APIs and tools, providing you with an access key and secret key. Then click on the button Next: Permissions. In the screen below, notice that a policy has been selected by default. Let the default settings as applied. This provides you full access to AWS services by enabling the AWS user (the current user you are creating) to be an administrator.

    在上面的屏幕中,确保已选中“ 程序访问” 。 它允许新用户以不同的API和工具的形式访问创建资源,从而为您提供访问密钥和秘密密钥。 然后单击按钮下一步:权限 。 在下面的屏幕中,请注意默认情况下已选择策略。 使用默认设置。 通过使AWS用户(您正在创建的当前用户)成为管理员,可以向您提供对AWS服务的完全访问权限。

    Then, click on Next: Tags. No modifications are required for the current use case.

    然后,点击下一步:标签 。 当前用例无需修改。

    Then, click on Next: Review. Again, no modifications are required. Click on the Create user button and you are directed to a new page where you find the Access Key and Secret Key. Go to your terminal window, press the enter key and when prompted enter the Access Key and the Secret Key sequentially. It is going to ask for a profile name. You can enter the project name or the username here.

    然后,单击下一步:查看 。 同样,无需修改。 单击“ 创建用户”按钮,您将被带到一个新页面,可在其中找到访问密钥和秘密密钥。 进入终端窗口,按Enter键,并在提示时依次输入访问键和秘密键。 它将要求一个配置文件名称。 您可以在此处输入项目名称或用户名。

    Pressing enter for the last time creates a new AWS user.

    最后一次按Enter键将创建一个新的AWS用户。

    将AWS Amplify集成到React Native中 (Integrating AWS Amplify in React Native)

    To initialize AWS Amplify with the React Native app, run the following command that in return prompts you for some more questions. Go back to the terminal window and run the initialization command as below:

    要使用React Native应用程序初始化AWS Amplify,请运行以下命令,该命令以回显方式提示您其他问题。 返回终端窗口并运行初始化命令,如下所示:

    amplify init

    After running this command, you are prompted with configuration questions. For the current demo, we are choosing all the default options. For your reference, you can find the options listed next to the question as shown below:

    运行此命令后,系统会提示您配置问题。 对于当前的演示,我们选择所有默认选项。 作为参考,您可以在问题旁边找到列出的选项,如下所示:

    After the Amplify SDK initialization process is complete, notice there are some new file changes inside the project directory. A new directory called amplify/that stores any local or cloud changes, is added to the root directory of the React Native project. A new file called aws-exports.jsappears at the root that you do not have commit at a public Github repository. The amplify initcommand takes care of this. It is going to update the.gitignore file in the React Native project.

    Amplify SDK初始化过程完成后,请注意项目目录中有一些新文件更改。 一个存储所有本地或云更改的名为amplify/新目录被添加到React Native项目的根目录中。 一个名为aws-exports.js新文件将出现在您尚未在公共Github存储库中提交的根目录下。 amplify init命令可以解决这个问题。 它会在React Native项目中更新.gitignore文件。

    To integrate Amplify SDK with the Expo or React Native app, install the following dependencies. Go back to the terminal window and execute the command:

    要将Amplify SDK与Expo或React Native应用程序集成,请安装以下依赖项。 返回终端窗口并执行命令:

    yarn add aws-amplify aws-amplify-react-native

    The package aws-amplify allows you to make requests to the auth and API services provided by AWS. The other package aws-amplify-react-native is framework-specific and contains ready-to-use UI components.

    软件包aws-amplify允许您向AWS提供的身份验证和API服务发出请求。 其他软件包aws-amplify-react-native是特定于框架的,并包含即用型UI组件。

    After these dependencies are installed, open the App.js file and add the following import statements.

    安装这些依赖项之后,打开App.js文件并添加以下导入语句。

    import config from './aws-exports'; Amplify.configure(config);

    That’s it to integrate Amplify with the Expo app.

    就是将Amplify与Expo应用程序集成在一起。

    添加放大身份验证资源 (Adding Amplify Authentication Resource)

    Amplify uses Amazon Cognito for authentication. Amazon Cognito is a fully-featured user directory that handles user registration, login, and account recovery. Amplify interfaces with Cognito User Pools to store user information, including social providers like Facebook, Google, and so on.

    Amplify使用Amazon Cognito进行身份验证。 Amazon Cognito是功能齐全的用户目录,用于处理用户注册,登录和帐户恢复。 放大与Cognito用户池的接口以存储用户信息,包括Facebook,Google等社交提供商。

    To add a user authentication with Amplify, start by running the command from a terminal window.

    要使用Amplify添加用户身份验证,请从终端窗口运行命令开始。

    amplify add auth

    After running the command, you are prompted with the following set of questions:

    运行命令后,系统将提示您以下问题:

    Do you want to use the default authentication and security configuration? Default configurationHow do you want users to be able to sign in? Email Do you want to configure advanced settings? No, I am done.

    The first option is to choose the default authentication and security configuration. Let’s leave to default. The second option is to use an auth provider. In our case, let’s selected Email. You can also add a social provider like Facebook or Google Sign-in.

    第一个选项是选择默认的身份验证和安全配置。 让我们保留默认值。 第二种选择是使用身份验证提供程序。 在本例中,我们选择“ Email 。 您还可以添加社交提供商,例如Facebook或Google登录。

    Now run the following command to publish all the local changes to AWS in order to create a user pool.

    现在运行以下命令以将所有本地更改发布到AWS,以便创建用户池。

    amplify push

    You get the following screen after you execute the above command. shows the details of the current working environment which is devand displays the status of the resource currently using which is Auth.

    执行上述命令后,将显示以下屏幕。 显示当前工作环境dev的详细信息,并显示当前正在使用的资源Auth 。

    Execution of command may take some time to push the changes to enable and create the user pool. Initializing the user authentication setup using Amazon Cognito is complete.

    执行命令可能需要一些时间才能推送更改以启用和创建用户池。 使用Amazon Cognito初始化用户身份验证设置已完成。

    构建注册和登录UI (Building the Registration and Login UI)

    Amplify comes with a High Order Component called withAuthenticatorthat is used to wrap the root component of the React Native app. Import it in the App.jsfile and then use it to wrap the App function component.

    Amplify带有一个名为withAuthenticator高阶组件,用于包装React Native应用程序的根组件。 将其导入App.js文件,然后使用其包装App函数组件。

    // ... after other import statementsimport { withAuthenticator } from 'aws-amplify-react-native';// ... contents of App componentfunction App() { return ( <View style={styles.container}> <Text>💙 + 💛 = React Native + Amplify </Text> <StatusBar style="auto" /> </View> );}// wrap the App component as shown belowexport default withAuthenticator(App);

    The withAuthenticator component renders the App component after a successful user sign-in, and it prevents non-sign-in users to interact with your app. It automatically detects the authentication state and updates the UI.

    withAuthenticator组件在用户成功登录后呈现App组件,并且它阻止非登录用户与您的应用进行交互。 它会自动检测身份验证状态并更新UI。

    Now, go back to the terminal window and start the Expo development server using the yarn start command.

    现在,返回到终端窗口,并使用yarn start命令启动Expo开发服务器。

    Once the app is loaded, you are going to get the following initial screen with some UI components already provided by the HOC used to wrap the App component.

    加载应用程序后,您将获得以下初始屏幕,其中包含由HOC提供的用于包装App组件的一些UI组件。

    Since there are no users, if you try to sign in, you won’t get access.

    由于没有用户,因此如果您尝试登录,将无法访问。

    AWS Amplify is so awesome in this manner that they even provide basic and useful details like when you attempt to sign in with a wrong user name, or a user name that does not exist, an error message is displayed.

    AWS Amplify如此出色,以至于它们甚至提供了基本和有用的详细信息,例如当您尝试使用错误的用户名登录或用户名不存在时,会显示一条错误消息。

    Click on the Sign-Up button below the Sign In button to go the registration screen and register a new user.

    单击“登录”按钮下方的“注册”按钮以进入注册屏幕并注册新用户。

    Make sure to enter a valid email in the fields Usernameand Email. It sends a verification code for the user to create a new account.

    确保在“ Username和“ Email ”字段中输入有效的Email 。 它发送验证码以供用户创建新帐户。

    Once the new user account is created, you are going to be re-directed back to the Sign In screen. To sign in, enter the same credentials you registered a new user with.

    创建新用户帐户后,您将被重定向回“登录”屏幕。 要登录,请输入与新用户注册相同的凭据。

    On successful sign-in, you are going to see the main application.

    成功登录后,您将看到主应用程序。

    在React Native中使用AWS Amplify添加注销功能 (Adding a Logout Functionality with AWS Amplify in React Native)

    To use the default UI component for signing out the user from the React Native app, you have to pass a second argument to the withAuthenticator High Order component when it wraps the App component.

    要使用默认的UI组件从React Native应用中注销用户,您必须在包装App组件时将第二个参数传递给withAuthenticator High Order组件。

    Modify the App.js file:

    修改App.js文件:

    export default withAuthenticator(App, true);

    This displays a sign-out button as shown below.

    这将显示一个注销按钮,如下所示。

    Start by importing the Authobject in the App.jsfile. Then, inside the Appfunction, create a new asynchronous handler method called signOutwhich uses the Auth.signOut() method.

    首先将Auth对象导入App.js文件。 然后,内部App的功能,创建一个新的名为异步处理程序方法signOut它使用Auth.signOut()方法。

    The custom method then is used as the value of the onPressprop on a Buttoncomponent from react-native.

    然后将自定义方法用作react-native上Button组件上onPress道具的值。

    // other import statementsimport { withAuthenticator } from 'aws-amplify-react-native';function App() { async function signOut() { try { await Auth.signOut(); } catch (error) { console.log('Error signing out: ', error); } }return ( <View style={styles.container}> <Text>💙 + 💛 = React Native + Amplify </Text> <Button title="Sign Out" color="tomato" onPress={signOut} /> <StatusBar style="auto" /> </View> );}// make sure to remove the second argumentexport default withAuthenticator(App);

    Here is the output you are going to get after this step:

    这是您将在此步骤之后获得的输出:

    On pressing the sign out button you are directed back to the login screen.

    按下退出按钮后,您将直接返回登录屏幕。

    使用React导航库创建自定义身份验证流程 (Creating a Custom Authentication Flow with React Navigation Library)

    This section onwards let’s learn how to create a custom authentication flow using React Navigation and create custom screens to sign-in, sign-up, confirm verification code, and sign out a user.

    从本节开始,我们将学习如何使用React Navigation创建自定义身份验证流程,以及如何创建自定义屏幕以登录,注册,确认验证码和注销用户。

    Start by adding the react-navigation library in the React Native app. Go back to the terminal window and install the following dependencies.

    首先在React Native应用程序中添加react-navigation库。 返回终端窗口并安装以下依赖项。

    expo install @react-navigation/native @react-navigation/stack react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

    Once the dependencies are installed, create the following directory structure. The screens/ directory contains all the different screen components. The components/ contains two re-usable components that are going to be used to build form screens.

    安装依赖项后,创建以下目录结构。 screens/目录包含所有不同的屏幕组件。 components/包含两个可重复使用的组件,这些组件将用于构建表单屏幕。

    ├──src/│ └──screens/│ └── SignIn.js│ └── SignUp.js│ └── ConfirmSignUp.js│ └── Home.js| └──components/│ └── AppButton.js│ └── AppTextInput.js

    Let’s start by building the re-usable components first. Add the following code snippet in AppButton.js file:

    让我们首先构建可重用组件。 在AppButton.js文件中添加以下代码片段:

    import React from 'react';import { StyleSheet, Text, TouchableOpacity } from 'react-native';export default function AppButton({ title, onPress }) { return ( <TouchableOpacity style={styles.button} onPress={onPress}> <Text style={styles.buttonText}>{title}</Text> </TouchableOpacity> );}const styles = StyleSheet.create({ button: { marginVertical: 10, borderRadius: 25, justifyContent: 'center', alignItems: 'center', padding: 15, width: '80%', backgroundColor: 'tomato' }, buttonText: { color: 'white', fontSize: 18, fontWeight: '600', textTransform: 'uppercase' }});

    The button component consists of a TouchableOpacityand a Textcomponent that receives the label of the button and onPresshandler method as props from the screen component it is going to be used in. Similarly, in the file AppTextInput.jsadd the code snippet that is going to display a TextInputfield along with an icon on the left of the input field. To display the icon, let's use the package@expo-vector-icons.

    按钮组件由一个TouchableOpacity和一个Text组件组成,该组件从将要使用的屏幕组件中接收按钮的标签和onPress处理程序方法作为道具。类似地,在文件AppTextInput.js添加以下代码段:将在输入字段的左侧显示一个TextInput字段以及一个图标。 要显示图标,请使用包@ expo-vector-icons 。

    import React from 'react';import { View, StyleSheet, TextInput } from 'react-native';import { MaterialCommunityIcons } from '@expo/vector-icons';export default function AppTextInput({ leftIcon, ...otherProps }) { return ( <View style={styles.container}> {leftIcon && ( <MaterialCommunityIcons name={leftIcon} size={20} color="#6e6869" style={styles.icon} /> )} <TextInput style={styles.input} placeholderTextColor="#6e6869" {...otherProps} /> </View> );}const styles = StyleSheet.create({ container: { backgroundColor: '#f9f9f9', borderRadius: 25, flexDirection: 'row', padding: 15, marginVertical: 10 }, icon: { marginRight: 10 }, input: { width: '80%', fontSize: 18, color: '#101010' }});

    In the next section, let’s build the first screen to allow a user to sign-in.

    在下一部分中,让我们构建第一个屏幕以允许用户登录。

    创建自定义登录屏幕 (Creating a Custom Sign In Screen)

    The SignIn.jsfile is going to contain two input fields and two buttons to let the user enter their credentials to log into the app. The screen is going to be similar in terms of working as you might have seen in an earlier default Sign-In screen that comes with Amplify's High Order Component withAuthenticator.

    SignIn.js文件将包含两个输入字段和两个按钮,以允许用户输入其凭据以登录应用程序。 屏幕的工作方式将与在Amplify的withAuthenticator的High Order Component随附的早期默认登录屏幕中看到的工作方式相似。

    The Authmodule from aws-amplifycontains all the methods to use with custom navigation flow. For example, in the code snippet below you are going to find Auth.signIn(username, password);to allow a user log into the app. The two arguments are going to be the user's credentials coming from the sign-in form. To keep track of the values for usernameand passwordfields, let's use React Hook useState.

    来自aws-amplify的Auth模块包含用于自定义导航流的所有方法。 例如,在下面的代码片段中,您将找到Auth.signIn(username, password); 允许用户登录该应用。 这两个参数将是来自登录表单的用户凭据。 为了跟踪username和password字段的值,让我们使用React Hook useState 。

    Ignore the updateAuthState prop for now. It becomes more clear on is it being used and for what when the configuration of the navigation flow is complete.

    现在updateAuthState忽略updateAuthState 。 可以更清楚地了解到它正在使用,以及导航流程的配置何时完成。

    import React, { useState } from 'react';import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';import { Auth } from 'aws-amplify';import { SafeAreaView } from 'react-native-safe-area-context';import AppTextInput from '../components/AppTextInput';import AppButton from '../components/AppButton';export default function SignIn({ navigation, updateAuthState }) { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); async function signIn() { try { await Auth.signIn(username, password); console.log('Success'); updateAuthState('loggedIn'); } catch (error) { console.log('Error signing in...', error); } } return ( <SafeAreaView style={styles.safeAreaContainer}> <View style={styles.container}> <Text style={styles.title}>Sign in to your account</Text> <AppTextInput value={username} onChangeText={text => setUsername(text)} leftIcon="account" placeholder="Enter username" autoCapitalize="none" keyboardType="email-address" textContentType="emailAddress" /> <AppTextInput value={password} onChangeText={text => setPassword(text)} leftIcon="lock" placeholder="Enter password" autoCapitalize="none" autoCorrect={false} secureTextEntry textContentType="password" /> <AppButton title="Login" onPress={signIn} /> <View style={styles.footerButtonContainer}> <TouchableOpacity onPress={() => navigation.navigate('SignUp')}> <Text style={styles.forgotPasswordButtonText}> Don't have an account? Sign Up </Text> </TouchableOpacity> </View> </View> </SafeAreaView> );}

    The second button is going to navigate the user to the Sign-Up screen using the navigation.navigate()function from react-navigation library.

    第二个按钮将使用react-navigation库中的navigation.navigate()函数将用户导航到“注册”屏幕。

    Add the following styles object:

    添加以下styles对象:

    const styles = StyleSheet.create({ safeAreaContainer: { flex: 1, backgroundColor: 'white' }, container: { flex: 1, alignItems: 'center' }, title: { fontSize: 20, color: '#202020', fontWeight: '500', marginVertical: 15 }, footerButtonContainer: { marginVertical: 15, justifyContent: 'center', alignItems: 'center' }, forgotPasswordButtonText: { color: 'tomato', fontSize: 18, fontWeight: '600' }});

    制作自定义注册屏幕 (Making a Custom Sign Up Screen)

    Creating a custom sign-up screen, you can control what user data or credentials you require for them to create a new account with your app. The custom sign-up screen code snippet is going to have three fields: username, password, and email.

    创建自定义注册屏幕后,您可以控制用户使用自己的应用程序创建新帐户所需的用户数据或凭据。 自定义注册屏幕代码段将包含三个字段: username , password和email 。

    The Auth.signUp({ username, password, attributes: { email } });is the method that successfully allows the user to create a new account. The attributesobject can have other fields such as phone_numberor other custom fields. The values passed through this object are always optional. With React Hook useState you can keep track of as many attributes as your app require.

    Auth.signUp({ username, password, attributes: { email } }); 是成功允许用户创建新帐户的方法。 attributes对象可以具有其他字段,例如phone_number或其他自定义字段。 通过此对象传递的值始终是可选的。 使用React Hook useState您可以跟踪应用程序所需的多个属性。

    Do note that the Amazon Cognito does not dynamically create custom attributes. In order to use a custom attribute, it has to be created in the user pool. More information on how to do this process with Amplify CLI is in the Amplify’s documentation here.

    请注意,Amazon Cognito不会动态创建自定义属性。 为了使用自定义属性,必须在用户池中创建它。 有关如何使用Amplify CLI执行此过程的更多信息,请参见此处的Amplify文档 。

    Open the file SignUp.js and add the following code snippet:

    打开文件SignUp.js并添加以下代码片段:

    import React, { useState } from 'react';import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';import { Auth } from 'aws-amplify';import { SafeAreaView } from 'react-native-safe-area-context';import AppTextInput from '../components/AppTextInput';import AppButton from '../components/AppButton';export default function SignUp({ navigation }) { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [email, setEmail] = useState('');async function signUp() { try { await Auth.signUp({ username, password, attributes: { email } }); console.log('✅ Sign-up Confirmed'); navigation.navigate('ConfirmSignUp'); } catch (error) { console.log('❌ Error signing up...', error); } }return ( <SafeAreaView style={styles.safeAreaContainer}> <View style={styles.container}> <Text style={styles.title}>Create a new account</Text> <AppTextInput value={username} onChangeText={text => setUsername(text)} leftIcon="account" placeholder="Enter username" autoCapitalize="none" keyboardType="email-address" textContentType="emailAddress" /> <AppTextInput value={password} onChangeText={text => setPassword(text)} leftIcon="lock" placeholder="Enter password" autoCapitalize="none" autoCorrect={false} secureTextEntry textContentType="password" /> <AppTextInput value={email} onChangeText={text => setEmail(text)} leftIcon="email" placeholder="Enter email" autoCapitalize="none" keyboardType="email-address" textContentType="emailAddress" /> <AppButton title="Sign Up" onPress={signUp} /> <View style={styles.footerButtonContainer}> <TouchableOpacity onPress={() => navigation.navigate('SignIn')}> <Text style={styles.forgotPasswordButtonText}> Already have an account? Sign In </Text> </TouchableOpacity> </View> </View> </SafeAreaView> );}

    The above component is going to have following styles:

    上面的组件将具有以下样式:

    const styles = StyleSheet.create({ safeAreaContainer: { flex: 1, backgroundColor: 'white' }, container: { flex: 1, alignItems: 'center' }, title: { fontSize: 20, color: '#202020', fontWeight: '500', marginVertical: 15 }, footerButtonContainer: { marginVertical: 15, justifyContent: 'center', alignItems: 'center' }, forgotPasswordButtonText: { color: 'tomato', fontSize: 18, fontWeight: '600' }});

    建立自定义验证码屏幕 (Building a Custom Verification Code Screen)

    Once the user creates a new account, they are directed to the Confirm Sign Up screen which is going to ask for the verification code. The Auth.confirmSignUp()method is used in this case. It takes two arguments: usernameand authCode. The authCode is what gets sent to the user's email as the verification code.

    用户创建新帐户后,他们将被定向到“确认注册”屏幕,该屏幕将要求输入验证码。 在这种情况下,将使用Auth.confirmSignUp()方法。 它authCode两个参数: username和authCode 。 authCode是作为验证码发送到用户电子邮件的内容。

    Add the following code snippet to the file ConfirmSignUp.js.

    将以下代码片段添加到文件ConfirmSignUp.js 。

    import React, { useState } from 'react';import { View, Text, StyleSheet } from 'react-native';import { Auth } from 'aws-amplify';import { SafeAreaView } from 'react-native-safe-area-context';import AppTextInput from '../components/AppTextInput';import AppButton from '../components/AppButton';export default function ConfirmSignUp({ navigation }) { const [username, setUsername] = useState(''); const [authCode, setAuthCode] = useState('');async function confirmSignUp() { try { await Auth.confirmSignUp(username, authCode); console.log('✅ Code confirmed'); navigation.navigate('SignIn'); } catch (error) { console.log( '❌ Verification code does not match. Please enter a valid verification code.', error.code ); } }return ( <SafeAreaView style={styles.safeAreaContainer}> <View style={styles.container}> <Text style={styles.title}>Confirm Sign Up</Text> <AppTextInput value={username} onChangeText={text => setUsername(text)} leftIcon="account" placeholder="Enter username" autoCapitalize="none" keyboardType="email-address" textContentType="emailAddress" /> <AppTextInput value={authCode} onChangeText={text => setAuthCode(text)} leftIcon="numeric" placeholder="Enter verification code" keyboardType="numeric" /> <AppButton title="Confirm Sign Up" onPress={confirmSignUp} /> </View> </SafeAreaView> );}

    In this screen, you can add more business logic to handle scenarios such as when the verification code entered by the user does not match the code sent to the user’s email. Once the verification code matches, the user is re-directed to the sign-in screen. The component is going to have the following styles:

    在此屏幕中,您可以添加更多业务逻辑来处理各种情况,例如,当用户输入的验证码与发送到用户电子邮件的验证码不匹配时。 验证码匹配后,用户将被重定向到登录屏幕。 该组件将具有以下样式:

    const styles = StyleSheet.create({ safeAreaContainer: { flex: 1, backgroundColor: 'white' }, container: { flex: 1, alignItems: 'center' }, title: { fontSize: 20, color: '#202020', fontWeight: '500', marginVertical: 15 }});

    使用退出按钮添加主屏幕 (Adding a Home Screen with Sign Out Button)

    The last screen in the current navigation flow is going to be a home screen with some text and a sign out button. The handler method behind the sign out button is the same as you have seen in the earlier sections of this tutorial. Add the following code snippet to Home.js file:

    当前导航流中的最后一个屏幕将是带有一些文本和退出按钮的主屏幕。 “退出”按钮后面的处理程序方法与本教程前面的部分相同。 将以下代码片段添加到Home.js文件中:

    import React from 'react';import { View, Text, StyleSheet, Button } from 'react-native';import { Auth } from 'aws-amplify';export default function Home({ updateAuthState }) { async function signOut() { try { await Auth.signOut(); updateAuthState('loggedOut'); } catch (error) { console.log('Error signing out: ', error); } }return ( <View style={styles.container}> <Text> 💙 + 💛</Text> <Button title="Sign Out" color="tomato" onPress={signOut} /> </View> );}const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', marginTop: 20 }});

    检查用户的登录状态 (Checking User’s Logged In State)

    The App.js file is going to contain all the custom navigation flow as well default Amplify configuration. Open the file and start by adding the following import statements:

    App.js文件将包含所有自定义导航流以及默认的Amplify配置。 打开文件并通过添加以下导入语句开始:

    import React, { useState, useEffect } from 'react';import { ActivityIndicator, View } from 'react-native';import Amplify, { Auth } from 'aws-amplify';import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';import config from './aws-exports';import SignIn from './src/screens/SignIn';import SignUp from './src/screens/SignUp';import ConfirmSignUp from './src/screens/ConfirmSignUp';import Home from './src/screens/Home';Amplify.configure(config);

    The navigation flow is going to be divided into two stacks. The first stack is called AuthenticationNavigator and has all screens related when the user is not logged in.

    导航流程将分为两个堆栈。 第一个堆栈称为AuthenticationNavigator ,当用户未登录时,所有屏幕都相关。

    The second stack navigator is called AppNavigator that has only one screen: the Home screen. This screen is only available if a user successfully logs in.

    第二个堆栈导航器称为AppNavigator ,它只有一个屏幕: Home屏幕。 仅当用户成功登录时,此屏幕才可用。

    const AuthenticationStack = createStackNavigator();const AppStack = createStackNavigator();const AuthenticationNavigator = props => { return ( <AuthenticationStack.Navigator headerMode="none"> <AuthenticationStack.Screen name="SignIn"> {screenProps => ( <SignIn {...screenProps} updateAuthState={props.updateAuthState} /> )} </AuthenticationStack.Screen> <AuthenticationStack.Screen name="SignUp" component={SignUp} /> <AuthenticationStack.Screen name="ConfirmSignUp" component={ConfirmSignUp} /> </AuthenticationStack.Navigator> );};const AppNavigator = props => { return ( <AppStack.Navigator> <AppStack.Screen name="Home"> {screenProps => ( <Home {...screenProps} updateAuthState={props.updateAuthState} /> )} </AppStack.Screen> </AppStack.Navigator> );};

    Let’s create a function component called Initializing which is going to be responsible to display a loading indicator when checking the state whether the user is logged in or not.

    让我们创建一个称为Initializing的功能组件,该组件将在检查用户是否登录状态时负责显示加载指示器。

    const Initializing = () => { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <ActivityIndicator size="large" color="tomato" /> </View> );};

    To check the state whether the user is logged in or not, in the Appcomponent defines a state variable called isUserLoggedIn. It has a default value of initializing which means that when the state of user's auth is being checked, the loading indicator is shown.

    为了检查用户是否已登录的状态,在App组件中定义了一个名为isUserLoggedIn的状态变量。 它具有initializing的默认值,这意味着在检查用户的身份验证状态时,将显示加载指示器。

    function App() { const [isUserLoggedIn, setUserLoggedIn] = useState('initializing'); // ...}

    Amplify’s Authobject provides a method called currentAuthenticatedUser() to check whether the user is logged or not in real-time. Add an asynchronous handler method called checkAuthStatewhich is going to process this task. Based on the result from the method, set the user's logged-in state by updating the value of the state variable using setUserLoggedIn(). On success, update the value to loggedIn. If there is an error or the user is not logged in, update the value to loggedOut.

    Amplify的Auth对象提供了一种称为currentAuthenticatedUser()的方法,用于检查用户是否实时登录。 添加一个名为checkAuthState的异步处理程序方法,该方法将处理此任务。 根据方法的结果,通过使用setUserLoggedIn()更新状态变量的值来设置用户的登录状态。 成功后,将值更新为loggedIn 。 如果出现错误或用户未登录,请将值更新为loggedOut 。

    Add another handler method called updateAuthStatethat is going to be passed as props to two screens: Homeand SignIn. Passing the prop is helpful since the state of auth changes at these two particular screens. Once the user signs in, update the value of setUserLoggedInto loggedIn using the prop and vice versa when the user signs out.

    添加另一个称为updateAuthState处理程序方法,该方法将作为道具传递给两个屏幕: Home和SignIn 。 传递道具很有用,因为在这两个特定屏幕上auth的状态会发生变化。 一旦用户登录,更新的价值setUserLoggedIn到loggedIn使用道具,反之亦然,当用户退出。

    function App() { // ...useEffect(() => { checkAuthState(); }, []);async function checkAuthState() { try { await Auth.currentAuthenticatedUser(); console.log('✅ User is signed in'); setUserLoggedIn('loggedIn'); } catch (err) { console.log('❌ User is not signed in'); setUserLoggedIn('loggedOut'); } }function updateAuthState(isUserLoggedIn) { setUserLoggedIn(isUserLoggedIn); }// ...}

    Then, return and wrap all the different conditions based on the value of isUserLoggedInstate variable inside NavigationContainerfrom the react-navigation library.

    然后,根据react-navigation库中NavigationContainer内部的isUserLoggedIn状态变量的值返回并包装所有不同的条件。

    function App() { { // ...return ( <NavigationContainer> {isUserLoggedIn === 'initializing' && <Initializing />} {isUserLoggedIn === 'loggedIn' && ( <AppNavigator updateAuthState={updateAuthState} /> )} {isUserLoggedIn === 'loggedOut' && ( <AuthenticationNavigator updateAuthState={updateAuthState} /> )} </NavigationContainer> ); }}export default App;

    运行AWS Amplify React Native Mobile App (Running the AWS Amplify React Native Mobile App)

    To start the Expo development server, execute the command yarn start. Go back to the simulator device or any other device you are using, and you are going to be welcome by the following SignIn screen.

    要启动Expo开发服务器,请执行命令yarn start 。 返回到模拟器设备或您正在使用的任何其他设备,以下SignIn屏幕将欢迎您。

    To create a new user, go to the SignUp screen. On successful sign-up, it is going to ask to verify the auth code.

    要创建一个新的用户,请访问SignUp屏幕。 成功注册后,将要求验证身份验证码。

    Once the code is verified, you are re-directed to the SignInscreen. On a successful log-in, you are going to see the Home screen.

    验证代码后,您将被SignIn到“ SignIn屏幕。 成功登录后,您将看到Home屏幕。

    摘要 (Summary)

    It has been a long post but we wanted to cover all the aspects to get started with setting up and configuring user authentication with AWS Amplify, Expo, and React Native apps.

    这是一篇很长的文章,但是我们想涵盖所有方面,以开始使用AWS Amplify,Expo和React Native应用程序设置和配置用户身份验证。

    As you can see the AWS Amplify framework, which bridges access to the AWS cloud services is an extremely powerful library, allowing us to implement critically secure features such as login, registration and logout with only a few lines of code, and in no time.

    如您所见,AWS Amplify框架是一个功能强大的库,该桥将对AWS云服务的访问桥接起来,是一个非常强大的库,它使我们能够立即用几行代码实现至关重要的安全功能,例如登录,注册和注销。

    At Instamobile, we are building ready to use React Native apps, backed by various backends, such as AWS Amplify or Firebase, in order to help developers make their own mobile apps much more quickly.

    在Instamobile ,我们正在构建准备使用由各种后端(例如AWS Amplify或Firebase)支持的React Native应用程序,以帮助开发人员更快地制作自己的移动应用程序。

    普通英语JavaScript (JavaScript In Plain English)

    Did you know that we have three publications and a YouTube channel? Find links to everything at plainenglish.io!

    您知道我们有三个出版物和一个YouTube频道吗? 在plainenglish.io上找到所有内容的链接!

    翻译自: https://medium.com/javascript-in-plain-english/the-ultimate-guide-for-integrate-aws-amplify-authentication-for-react-native-15a8eec10890

    aws 集成

    相关资源:四史答题软件安装包exe
    Processed: 0.012, SQL: 8