The next feature you will be adding is authentication.
Amplify uses Amazon Cognito as its authentication provider. Amazon Cognito is a robust user directory service that handles user registration, authentication, account recovery & other operations. In this tutorial, you'll learn how to add authentication to your application using Amazon Cognito and username/password login.
To add authentication to your app, run this command:
amplify add auth
Select the defaults for the following prompts:
? Do you want to use the default authentication and security configuration? Default configuration
Warning: you will not be able to edit these selections.
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings? No, I am done.
To deploy the service, run the push
command:
amplify push
Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command:
amplify console
Creating a login flow can be quite difficult and time consuming to get right. Luckily, Amplify UI has an Authenticator
component that provides an entire authentication flow for you, using the configuration you specified in amplifyconfiguration.json.
The @aws-amplify/ui-react-native
package includes React Native specific UI components you'll use to build your app. Install it with the following command:
npm install @aws-amplify/ui-react-native react-native-safe-area-context@^4.2.5 react-native-get-random-values react-native-url-polyfill
npm install @aws-amplify/ui-react-native react-native-safe-area-context@^4.2.5 react-native-get-random-values react-native-url-polyfill
You will also need to install the pod dependencies for iOS:
npx pod-install
After installing pod dependencies, rebuild the app:
npm run ios
Open App.js and make the following changes:
Open App.tsx and make the following changes:
- Import the
withAuthenticator
Higher-Order Component anduseAuthenticator
hook:
import { withAuthenticator, useAuthenticator } from '@aws-amplify/ui-react-native';
- Create a custom
SignOutButton
component that will be used within the App component and only re-render when itsuser
context changes. Destructure theuser
andsignOut
properties returned from the hook.
// retrieves only the current value of 'user' from 'useAuthenticator'
const userSelector = (context) => [context.user]
const SignOutButton = () => {
const { user, signOut } = useAuthenticator(userSelector);
return (
<Pressable onPress={signOut} style={styles.buttonContainer}>
<Text style={styles.buttonText}>Hello, {user.username}! Click here to sign out!</Text>
</Pressable>
)
};
- Add the
SignOutButton
component to yourApp
component inside of the containers you defined in the last section:
// ...
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<SignOutButton />
//...
- Lastly, wrap your
App
export with thewithAuthenticator
Amplify UI component:
export default withAuthenticator(App);
Run the app to see the new authentication flow protecting the app:
npm start
Now you should see the app load with an authentication flow allowing users to sign up and sign in. Below you can find a full sample of the code:
import React, {useEffect, useState} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Pressable,
SafeAreaView,
} from 'react-native';
import {generateClient} from 'aws-amplify/api';
import {createTodo} from './src/graphql/mutations';
import {listTodos} from './src/graphql/queries';
import {
withAuthenticator,
useAuthenticator,
} from '@aws-amplify/ui-react-native';
import { Amplify } from 'aws-amplify';
import amplifyconfig from './src/amplifyconfiguration.json';
Amplify.configure(awsExports);
// retrieves only the current value of 'user' from 'useAuthenticator'
const userSelector = (context) => [context.user]
const SignOutButton = () => {
const { user, signOut } = useAuthenticator(userSelector);
return (
<Pressable onPress={signOut} style={styles.buttonContainer}>
<Text style={styles.buttonText}>
Hello, {user.username}! Click here to sign out!
</Text>
</Pressable>
);
};
const initialFormState = {name: '', description: ''};
const client = generateClient();
const App = () => {
const [formState, setFormState] = useState(initialFormState);
const [todos, setTodos] = useState([]);
useEffect(() => {
fetchTodos();
}, []);
function setInput(key, value) {
setFormState({...formState, [key]: value});
}
async function fetchTodos() {
try {
const todoData = await client.graphql({
query: listTodos
});
const todos = todoData.data.listTodos.items;
setTodos(todos);
} catch (err) {
console.log('error fetching todos');
}
}
async function addTodo() {
try {
if (!formState.name || !formState.description) return;
const todo = {...formState};
setTodos([...todos, todo]);
setFormState(initialFormState);
await client.graphql({
query: createTodo,
variables: { input: todo }
});
} catch (err) {
console.log('error creating todo:', err);
}
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<SignOutButton />
<TextInput
onChangeText={value => setInput('name', value)}
style={styles.input}
value={formState.name}
placeholder="Name"
/>
<TextInput
onChangeText={value => setInput('description', value)}
style={styles.input}
value={formState.description}
placeholder="Description"
/>
<Pressable onPress={addTodo} style={styles.buttonContainer}>
<Text style={styles.buttonText}>Create todo</Text>
</Pressable>
{todos.map((todo, index) => (
<View key={todo.id ? todo.id : index} style={styles.todo}>
<Text style={styles.todoName}>{todo.name}</Text>
<Text style={styles.todoDescription}>{todo.description}</Text>
</View>
))}
</View>
</SafeAreaView>
);
};
export default withAuthenticator(App);
const styles = StyleSheet.create({
container: {width: 400, flex: 1, padding: 20, alignSelf: 'center'},
todo: {marginBottom: 15},
input: {backgroundColor: '#ddd', marginBottom: 10, padding: 8, fontSize: 18},
todoName: {fontSize: 20, fontWeight: 'bold'},
buttonContainer: {
alignSelf: 'center',
backgroundColor: 'black',
paddingHorizontal: 8,
},
buttonText: {color: 'white', padding: 16, fontSize: 18},
});
import React, {useEffect, useState} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Pressable,
SafeAreaView,
} from 'react-native';
import {generateClient} from 'aws-amplify/api';
import {createTodo} from './src/graphql/mutations';
import {listTodos} from './src/graphql/queries';
import {
withAuthenticator,
useAuthenticator,
} from '@aws-amplify/ui-react-native';
// retrieves only the current value of 'user' from 'useAuthenticator'
const userSelector = (context) => [context.user]
const SignOutButton = () => {
const { user, signOut } = useAuthenticator(userSelector);
return (
<Pressable onPress={signOut} style={styles.buttonContainer}>
<Text style={styles.buttonText}>
Hello, {user.username}! Click here to sign out!
</Text>
</Pressable>
);
};
const initialFormState = {name: '', description: ''};
const client = generateClient();
const App = () => {
const [formState, setFormState] = useState(initialFormState);
const [todos, setTodos] = useState([]);
useEffect(() => {
fetchTodos();
}, []);
function setInput(key, value) {
setFormState({...formState, [key]: value});
}
async function fetchTodos() {
try {
const todoData = await client.graphql({
query: listTodos
});
const todos = todoData.data.listTodos.items;
setTodos(todos);
} catch (err) {
console.log('error fetching todos');
}
}
async function addTodo() {
try {
if (!formState.name || !formState.description) return;
const todo = {...formState};
setTodos([...todos, todo]);
setFormState(initialFormState);
await client.graphql({
query: createTodo,
variables: {input: todo}
});
} catch (err) {
console.log('error creating todo:', err);
}
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<SignOutButton />
<TextInput
onChangeText={value => setInput('name', value)}
style={styles.input}
value={formState.name}
placeholder="Name"
/>
<TextInput
onChangeText={value => setInput('description', value)}
style={styles.input}
value={formState.description}
placeholder="Description"
/>
<Pressable onPress={addTodo} style={styles.buttonContainer}>
<Text style={styles.buttonText}>Create todo</Text>
</Pressable>
{todos.map((todo, index) => (
<View key={todo.id ? todo.id : index} style={styles.todo}>
<Text style={styles.todoName}>{todo.name}</Text>
<Text style={styles.todoDescription}>{todo.description}</Text>
</View>
))}
</View>
</SafeAreaView>
);
};
export default withAuthenticator(App);
const styles = StyleSheet.create({
container: {width: 400, flex: 1, padding: 20, alignSelf: 'center'},
todo: {marginBottom: 15},
input: {backgroundColor: '#ddd', marginBottom: 10, padding: 8, fontSize: 18},
todoName: {fontSize: 20, fontWeight: 'bold'},
buttonContainer: {
alignSelf: 'center',
backgroundColor: 'black',
paddingHorizontal: 8,
},
buttonText: {color: 'white', padding: 16, fontSize: 18},
});
Using Amplify UI connected components makes it easier to manage styling across your entire app.
In this example, you used the Amplify React UI library and the withAuthenticator
Higher-Order Component to quickly get up and running with a real-world authentication flow.
You can also customize this component to add or remove fields, update styling, or other configurations. You can even override function calls if needed.
In addition to withAuthenticator
, you can build custom authentication flows with the Amplify Library for JS. Amplify's Auth category has over 30 APIs including signUp
, signIn
, forgotPassword
, and signOut
that allow you full control over all aspects of the user authentication flow. Check out the complete API here.