Firstly, the standard UI from Amplify does not always meet customer UX requirements
Secondly, in the official documentation of Amplify it is stated that:
Data is stored unencrypted when using standard storage adapters (localStorage in the browser and AsyncStorage on React Native). Amplify gives you the option to use your own storage object to persist data. With this, you could write a thin wrapper around libraries like:
react-native-keychain
react-native-secure-storage
Expoβs secure store
This means that the authentication data is stored in an unencrypted form, and this is a risk
π· of information security with possible negative consequences πΈ.
Source code for this part is available on GitHub .
Clone the repository# Install the repository with the pre-installed UI Kit
Go to the project folder
Install dependencies
yarn
or
npm install
Initializing AWS Amplify in a React Native Project# Initialize our AWS Amplify project in the root directory.
Answer these questions:
The project successfully initialized π
Connect authentication plugin# Now that the application is in the cloud, you can add some features, such as allowing users to register with our application and log in.
Use command:
Connect the authentication function. Select the default configuration. This adds auth resource configurations locally to your ampify/backend/auth directory
π Select the profile we want to use. default. Enter and how users will log in. Email (write off money for SMS).
Submit changes to the cloud π
β All resources are updated in the cloud
Connect AWS Amplify to React Native# Details can be found in this instruction π.In short, you can add these dependencies below to connect AWS Amplify:
After installation, make sure to go to the ios folder and set the pods
Add navigation# install react-navigation v5, based on this instruction here
(at the time of writing this article this is latest version of navigation)
Add pods for iOS
π I recommend to launch the application for iOS and Android, after each installation, in order to avoid searching for the library because of which the application crashes.
react-native-keychain# Add react-native-keychain - this is a secure keystore library for React Native.
Add pods for iOS
According to official documentation:
When using authentication with AWS Amplify, you donβt have to update Amazon Cognito tokens manually. Tokens are automatically updated by the library when necessary. Security tokens, such as IdToken or AccessToken, are stored in localStorage for the browser and in AsyncStorage for React Native. If you want to store these tokens in a more secure place or use Amplify on the server side, you can provide your own storage object for storing these tokens.
configure src/index.tsx
For client authorization AppSync supports API Keys, Amazon IAM credentials, Amazon Cognito User Pools, and 3rd party OIDC providers. This is inferred from the aws-exports.js file when you call Amplify.configure().
When using Authentication with AWS Amplify, you donβt need to refresh Amazon Cognito tokens manually. The tokens are automatically refreshed by the library when necessary.
Security Tokens like IdToken or AccessToken are stored in localStorage for the browser and in AsyncStorage for React Native. If you want to store those tokens in a more secure place or you are using Amplify in server side, then you can provide your own storage object to store those tokens.
AppNavigator# Create a navigation configuration file for our custom authentication src/AppNavigator.tsx
Add a welcome screen to it.
Hello screen# Create an entry point for our authentication screens src/screens/Authenticator/index.ts
To begin with, let's connect welcome screen
After we create it src/screens/Authenticator/Hello/index.tsx
In the useEffect hook, we check for a user token, where in the case of true we go to the User screen, and in the case of false, we remain on this screen.
Put together all changes and meet the welcome screen.
SignUp screen# We create the registration screen SIGN_UP src/screens/Authenticator/SignUp/index.tsx, where for authentication we use the Auth.signUp method.
import React , { useState , ReactElement } from 'react'
import { Auth } from 'aws-amplify'
import * as Keychain from 'react-native-keychain'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { StackNavigationProp } from '@react-navigation/stack'
import { AppContainer , Space , Button , Input , TextError } from '../../../components'
import { onScreen , goBack } from '../../../constants'
import { RootStackParamList } from '../../../AppNavigator'
type ProfileScreenNavigationProp = StackNavigationProp < RootStackParamList , 'SIGN_UP' >
type SignUpT = {
navigation : ProfileScreenNavigationProp
}
const SignUp = ( { navigation } : SignUpT ) : ReactElement => {
const [ loading , setLoading ] = useState ( false )
const [ error , setError ] = useState ( '' )
const _onPress = async ( values : { email : string ; password : string ; passwordConfirmation : string } ) : Promise < void > => {
const { email , password , passwordConfirmation } = values
if ( password !== passwordConfirmation ) {
setError ( 'Passwords do not match!' )
} else {
setLoading ( true )
setError ( '' )
try {
const user = await Auth . signUp ( email , password )
await Keychain . setInternetCredentials ( 'auth' , email , password )
user && onScreen ( 'CONFIRM_SIGN_UP' , navigation , { email , password } ) ( )
setLoading ( false )
} catch ( err ) {
setLoading ( false )
if ( err . code === 'UserNotConfirmedException' ) {
setError ( 'Account not verified yet' )
} else if ( err . code === 'PasswordResetRequiredException' ) {
setError ( 'Existing user found. Please reset your password' )
} else if ( err . code === 'NotAuthorizedException' ) {
setError ( 'Forgot Password?' )
} else if ( err . code === 'UserNotFoundException' ) {
setError ( 'User does not exist!' )
} else {
setError ( err . code )
}
}
}
}
return (
< >
< AppContainer onPress = { goBack ( navigation ) } title = " Sign Up " loading = { loading } >
< Formik
initialValues = { { email : '' , password : '' , passwordConfirmation : '' } }
onSubmit = { ( values ) : Promise < void > => _onPress ( values ) }
validationSchema = { Yup . object ( ) . shape ( {
email : Yup . string ( )
. email ( )
. required ( ) ,
password : Yup . string ( )
. min ( 6 )
. required ( ) ,
passwordConfirmation : Yup . string ( )
. min ( 6 )
. required ( )
} ) }
>
{ ( { values , handleChange , errors , setFieldTouched , touched , handleSubmit } ) : ReactElement => (
< >
< Input
name = " email "
value = { values . email }
onChangeText = { handleChange ( 'email' ) }
onBlur = { ( ) : void => setFieldTouched ( 'email' ) }
placeholder = " E-mail "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
/>
< Input
name = " password "
value = { values . password }
onChangeText = { handleChange ( 'password' ) }
onBlur = { ( ) : void => setFieldTouched ( 'password' ) }
placeholder = " Password "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
secureTextEntry
/>
< Input
name = " passwordConfirmation "
value = { values . passwordConfirmation }
onChangeText = { handleChange ( 'passwordConfirmation' ) }
onBlur = { ( ) : void => setFieldTouched ( 'passwordConfirmation' ) }
placeholder = " Password confirm "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
secureTextEntry
/>
< Space height = { 30 } />
{ error !== '' && < TextError title = { error } textStyle = { { alignSelf : 'center' } } /> }
< Button title = " Sign Up " onPress = { handleSubmit } />
</ >
) }
</ Formik >
</ AppContainer >
</ >
)
}
export { SignUp }
Copy
ConfirmSignUp screen# After a successful response from the server, we go to the confirmation screen and enter the code that came to our mail. To do this, create the screen CONFIRM_SIGN_UP src/screens/Authenticator/ConfirmSignUp/index.tsx
import React , { useState , ReactElement } from 'react'
import { Auth } from 'aws-amplify'
import { Formik } from 'formik'
import { StackNavigationProp } from '@react-navigation/stack'
import { RouteProp } from '@react-navigation/native'
import * as Yup from 'yup'
import { AppContainer , Button , Space , ButtonLink , TextError , Input } from '../../../components'
import { onScreen , goBack } from '../../../constants'
import { RootStackParamList } from '../../../AppNavigator'
type ProfileScreenNavigationProp = StackNavigationProp < RootStackParamList , 'CONFIRM_SIGN_UP' >
type ProfileScreenRouteProp = RouteProp < RootStackParamList , 'CONFIRM_SIGN_UP' >
type ConfirmSignUpT = {
navigation : ProfileScreenNavigationProp
route : ProfileScreenRouteProp
}
const ConfirmSignUp = ( { route , navigation } : ConfirmSignUpT ) : ReactElement => {
const [ loading , setLoading ] = useState ( false )
const [ error , setError ] = useState ( '' )
const _onPress = async ( values : { code : string } ) : Promise < void > => {
setLoading ( true )
setError ( '' )
try {
const { code } = values
const { email , password } = route . params
await Auth . confirmSignUp ( email , code , { forceAliasCreation : true } )
const user = await Auth . signIn ( email , password )
user && onScreen ( 'USER' , navigation ) ( )
setLoading ( false )
} catch ( err ) {
setLoading ( false )
setError ( err . message )
if ( err . code === 'UserNotConfirmedException' ) {
setError ( 'Account not verified yet' )
} else if ( err . code === 'PasswordResetRequiredException' ) {
setError ( 'Existing user found. Please reset your password' )
} else if ( err . code === 'NotAuthorizedException' ) {
setError ( 'Forgot Password?' )
} else if ( err . code === 'UserNotFoundException' ) {
setError ( 'User does not exist!' )
}
}
}
const _onResend = async ( ) : Promise < void > => {
try {
const { email } = route . params
await Auth . resendSignUp ( email )
} catch ( err ) {
setError ( err . message )
}
}
return (
< >
< AppContainer title = " Confirmation " onPress = { goBack ( navigation ) } loading = { loading } >
< Formik
initialValues = { { code : '' } }
onSubmit = { ( values ) : Promise < void > => _onPress ( values ) }
validationSchema = { Yup . object ( ) . shape ( {
code : Yup . string ( ) . min ( 6 ) . required ( )
} ) }
>
{ ( { values , handleChange , errors , setFieldTouched , touched , handleSubmit } ) : ReactElement => (
< >
< Space height = { 180 } />
< Input
name = " code "
value = { values . code }
onChangeText = { handleChange ( 'code' ) }
onBlur = { ( ) : void => setFieldTouched ( 'code' ) }
placeholder = " Insert code "
touched = { touched }
errors = { errors }
/>
< ButtonLink title = " Resend code? " onPress = { _onResend } textStyle = { { alignSelf : 'center' } } />
{ error !== 'Forgot Password?' && < TextError title = { error } /> }
< Button title = " Confirm " onPress = { handleSubmit } />
< Space height = { 50 } />
</ >
) }
</ Formik >
</ AppContainer >
</ >
)
}
export { ConfirmSignUp }
Copy ResendSignUp# If the code has not arrived, then we must provide the user with the opportunity to resend the code.
To do this, we put Auth.resendSignUp(userInfo.email) on button Resend code.
In case of a successful method call
we must call the method
User screen# Once it successfully done, go to the USER screen, which we create with the exit button for the application and clearing the src/screens/Authenticator/User/index.tsx tokens
SignIn screen# After the user is registered, we must provide the user with the opportunity to enter the application through login and password. To do this, we create the SIGN_IN src/screens/Authenticator/SignIn/index.tsx screen
import React , { useState , ReactElement } from 'react'
import { Auth } from 'aws-amplify'
import * as Keychain from 'react-native-keychain'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { StackNavigationProp } from '@react-navigation/stack'
import { AppContainer , Button , Space , ButtonLink , TextError , Input } from '../../../components'
import { onScreen , goBack } from '../../../constants'
import { RootStackParamList } from '../../../AppNavigator'
type ProfileScreenNavigationProp = StackNavigationProp < RootStackParamList , 'SIGN_IN' >
type SignUpT = {
navigation : ProfileScreenNavigationProp
}
const SignIn = ( { navigation } : SignUpT ) : ReactElement => {
const [ userInfo , setUserInfo ] = useState ( { email : '' , password : '' } )
const [ loading , setLoading ] = useState ( false )
const [ error , setError ] = useState ( '' )
const _onPress = async ( values : { email : string ; password : string } ) : Promise < void > => {
setLoading ( true )
setError ( '' )
try {
const { email , password } = values
const user = await Auth . signIn ( email , password )
await Keychain . setInternetCredentials ( 'auth' , email , password )
user && onScreen ( 'USER' , navigation ) ( )
setLoading ( false )
} catch ( { code } ) {
setLoading ( false )
if ( code === 'UserNotConfirmedException' ) {
setError ( 'Account not verified yet' )
} else if ( code === 'PasswordResetRequiredException' ) {
setError ( 'Existing user found. Please reset your password' )
} else if ( code === 'NotAuthorizedException' ) {
setUserInfo ( values )
setError ( 'Forgot Password?' )
} else if ( code === 'UserNotFoundException' ) {
setError ( 'User does not exist!' )
} else {
setError ( code )
}
}
}
return (
< >
< AppContainer onPress = { goBack ( navigation ) } title = " Sign In " loading = { loading } message = { error } >
< Formik
enableReinitialize
initialValues = { userInfo }
onSubmit = { ( values ) : Promise < void > => _onPress ( values ) }
validationSchema = { Yup . object ( ) . shape ( {
email : Yup . string ( )
. email ( )
. required ( ) ,
password : Yup . string ( )
. min ( 6 )
. required ( )
} ) }
>
{ ( { values , handleChange , errors , setFieldTouched , touched , handleSubmit } ) : ReactElement => (
< >
< Space height = { 90 } />
< Input
name = " email "
value = { values . email }
onChangeText = { handleChange ( 'email' ) }
onBlur = { ( ) : void => setFieldTouched ( 'email' ) }
placeholder = " E-mail "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
/>
< Input
name = " password "
value = { values . password }
onChangeText = { handleChange ( 'password' ) }
onBlur = { ( ) : void => setFieldTouched ( 'password' ) }
placeholder = " Password "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
secureTextEntry
/>
{ error !== 'Forgot Password?' && < TextError title = { error } textStyle = { { alignSelf : 'center' } } /> }
{ error === 'Forgot Password?' && (
< ButtonLink
title = { error }
onPress = { onScreen ( 'FORGOT' , navigation , userInfo ) }
textStyle = { { alignSelf : 'center' } }
/>
) }
< Button title = " Sign In " onPress = { handleSubmit } />
< Space height = { 130 } />
</ >
) }
</ Formik >
</ AppContainer >
</ >
)
}
export { SignIn }
Copy
Forgot password screen# If successful, we send the user to the USER screen, which we have already done, and if the user has forgotten or entered the password incorrectly, then we show the Forgot Password error and suggest resetting the password.
To do this, we create the FORGOT src/screens/Authenticator/Forgot/index.tsx screen
Forgot password submit# After confirming the e-mail, we call the Auth.forgotPassword (email) method and if there is such a user, we send the user to the FORGOT_PASSWORD_SUBMIT src/screens/Authenticator/ForgotPassSubmit/index.tsx screen
import React , { useState , ReactElement } from 'react'
import { Auth } from 'aws-amplify'
import * as Keychain from 'react-native-keychain'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { StackNavigationProp } from '@react-navigation/stack'
import { RouteProp } from '@react-navigation/native'
import { AppContainer , Button , Space , Input , TextError } from '../../../components'
import { onScreen , goBack } from '../../../constants'
import { RootStackParamList } from '../../../AppNavigator'
type ProfileScreenNavigationProp = StackNavigationProp < RootStackParamList , 'FORGOT_PASSWORD_SUBMIT' >
type ProfileScreenRouteProp = RouteProp < RootStackParamList , 'FORGOT_PASSWORD_SUBMIT' >
type ForgotPassSubmitT = {
navigation : ProfileScreenNavigationProp
route : ProfileScreenRouteProp
}
const ForgotPassSubmit = ( { route , navigation } : ForgotPassSubmitT ) : ReactElement => {
const [ loading , setLoading ] = useState ( false )
const [ error , setError ] = useState ( '' )
const _onPress = async ( values : { email : string ; password : string ; code : string } ) : Promise < void > => {
setLoading ( true )
try {
const { email , code , password } = values
await Auth . forgotPasswordSubmit ( email , code , password )
await Keychain . setInternetCredentials ( 'auth' , email , password )
await Auth . signIn ( email , password )
onScreen ( 'USER' , navigation ) ( )
setLoading ( false )
} catch ( err ) {
setLoading ( false )
setError ( err . message )
}
}
return (
< >
< AppContainer title = " Confirmation " onPress = { goBack ( navigation ) } loading = { loading } message = { error } >
< Formik
initialValues = { { email : route . params . email || '' , code : '' , password : '' , passwordConfirmation : '' } }
onSubmit = { ( values ) : Promise < void > => _onPress ( values ) }
validationSchema = { Yup . object ( ) . shape ( {
email : Yup . string ( )
. email ( )
. required ( ) ,
code : Yup . string ( )
. min ( 6 )
. required ( ) ,
password : Yup . string ( )
. min ( 6 )
. required ( ) ,
passwordConfirmation : Yup . string ( )
. min ( 6 )
. required ( )
} ) }
>
{ ( { values , handleChange , errors , setFieldTouched , touched , handleSubmit } ) : ReactElement => (
< >
< Input
name = " email "
value = { values . email }
onChangeText = { handleChange ( 'email' ) }
onBlur = { ( ) : void => setFieldTouched ( 'email' ) }
placeholder = " E-mail "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
/>
< Input
name = " code "
value = { values . code }
onChangeText = { handleChange ( 'code' ) }
onBlur = { ( ) : void => setFieldTouched ( 'code' ) }
placeholder = " Code "
touched = { touched }
errors = { errors }
/>
< Input
name = " password "
value = { values . password }
onChangeText = { handleChange ( 'password' ) }
onBlur = { ( ) : void => setFieldTouched ( 'password' ) }
placeholder = " Password "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
secureTextEntry
/>
< Input
name = " passwordConfirmation "
value = { values . passwordConfirmation }
onChangeText = { handleChange ( 'passwordConfirmation' ) }
onBlur = { ( ) : void => setFieldTouched ( 'passwordConfirmation' ) }
placeholder = " Password confirm "
touched = { touched }
errors = { errors }
autoCapitalize = " none "
secureTextEntry
/>
{ error !== '' && < TextError title = { error } textStyle = { { alignSelf : 'center' } } /> }
< Space height = { 30 } />
< Button title = " Confirm " onPress = { handleSubmit } />
< Space height = { 80 } />
</ >
) }
</ Formik >
</ AppContainer >
</ >
)
}
export { ForgotPassSubmit }
Copy where, after entering the code sent to the mail, the new password and confirming it, we call the password change method
whose success sends the user to the USER screen.
Linking screens# We connect all created components in src/screens/Authenticator/index.ts
Udpate AppNavigator# Updating the navigation configuration file src/AppNavigator.tsx :
Debug# In order to understand what happens with tokens in your application, add in the root/index.js
We launch the application and get custom authentication.
Done β
#