Amplify 是 AWS 提供的開發工具,集前後端服務為一體(個人覺得是firebase的進階版),所以它並不是專門用來做身份驗證的,只不過是有包括這個服務而已。
Amplify 主要功能有:
使用AWS Amplify進行身份驗證有以下優點:
說那麼多其實就是看中 AWS 這座靠山,什麼服務都有就不需要考量太多 XD
而且 Amplify 提供了一套身份驗證的 API,基本的註冊、登入、忘記密碼、重設密碼、自動登入、記住裝置、第三方登入...等都有
因為要使用的是 AWS 服務,所以我們會需要先註冊 AWS 帳號,這邊就直接省略這步了。
npm install -g @aws-amplify/cli
amplify configure
~/.amplify 的訪問權限後再輸入一次指令:
sudo chown -R $(whoami):$(id -gn) ~/.amplify
amplify configure
 
 

 


 
default 即可


 
在根目錄輸入指令初始化 Amplify:
amplify init
根據自己專案的需求回答每個問題:
? Enter a name for the project (demo_app) 
The following configuration will be applied:
Project information
| Name: demo_app
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react-native
| Source Directory Path: src
| Distribution Directory Path: /
| Build Command: npm run-script build
| Start Command: npm run-script start
? Initialize the project with the above configuration? Yes
Using default provider:  awscloudformation
? Select the authentication method you want to use: AWS profile
? Please choose the profile you want to use: default

完成後專案中會多了 amplify 資料夾以及 aws-exports.js,這些我們不需要去動它,都是自動生成的,之後有修改設置會再自動重新生成。
輸入指令新增 auth 服務到專案中,並且選擇用戶要使用什麼作為用戶名登入應用:
amplify add auth
// 1. Default configuration
// 2. Email
// 3. No, I am done

完成設置後將設置推到 AWS 雲上:
amplify push

以上的設置完成之後,我們就可以開始在專案中寫身份驗證相關的 code 了。
首先需要安裝 aws-amplify, amazon-cognito-identity-js 以及相關依賴:
npm install aws-amplify amazon-cognito-identity-js @react-native-community/netinfo @react-native-async-storage/async-storage
npx pod-install
在 App.tsx 中新增:
// App.tsx
import { Amplify } from 'aws-amplify'
import awsconfig from './aws-exports'
Amplify.configure(awsconfig)
一切都設置完成後就可以使用 aws-amplify 提供的身份驗證相關 API 來實作簡單的身份驗證流程,下面是登入、登出和註冊的基本寫法:
import { Auth } from 'aws-amplify'
type SignUpParameters = {
  email: string
  password: string
}
const signUp = async ({ email, password }: SignUpParameters) {
  try {
    const { user } = await Auth.signUp({ email, password })
    console.log(user)
  } catch (error) {
    console.log('error signing up:', error)
  }
}
type ConfirmSignUpParameters = {
  email: string
  code: string
}
const confirmSignUp = async ({ email, code }: ConfirmSignUpParameters) => {
  try {
    await Auth.confirmSignUp(email, code)
  } catch (error) {
    console.log('error confirming sign up', error)
  }
}
import { Auth } from 'aws-amplify'
type SignInParameters = {
  username: string
  password: string
}
const signIn = async ({ username, password }: SignInParameters) => {
  try {
    const user = await Auth.signIn(username, password)
  } catch (error) {
    console.log('error signing in', error)
  }
}
import { Auth } from 'aws-amplify'
const signOut = async () => {
  try {
    await Auth.signOut()
  } catch (error) {
    console.log('error signing out: ', error)
  }
}
Auth.signIn 成功後會調用 getUserAuth.currentAuthenticatedUser 用於獲取當前經過身份驗證的用戶資料Auth.signOut 後會將 user 設為 nulluser 是否為 null 來判斷當前登入狀態import { useState, useEffect } from 'react'
import { Auth, Hub } from 'aws-amplify'
const App = () => {
    const [user, setUser] = useState(null)
    useEffect(() => {
        const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => {
          switch (event) {
            case 'signIn':
              getUser()
              break
            case 'signOut':
              setUser(null)
              break
            case 'signIn_failure':
              console.log('Sign in failure', data)
              break
          }
        })
        getUser()
        return unsubscribe
    }, []);
    const getUser = async (): Promise<void> => {
        try {
          const currentUser = await Auth.currentAuthenticatedUser()
          setUser(currentUser)
        } catch(error) {
          console.error(error)
        }
    }
    
    // ...
}
那最基本的部分就已經完成了,是不是非常容易XD
下一篇要說的是第三方登入(Google),還有忘記密碼、重設密碼的部分。