如何在 Amazon Cognito 中自動確認使用者?

3 分的閱讀內容
0

我想要確認使用者,然後在不使用一次性密碼 (OTP) 的情況下,自動驗證其電子郵件地址和電話號碼。

簡短描述

若使用者透過 Amazon Cognito 使用者集區註冊,則他們通常必須驗證其電子郵件地址或電話號碼。這通常是透過傳送 OTP 到使用者電子郵件地址或電話號碼進行驗證。使用者還可以在不使用 OTP 驗證的情況下自動確認。

以下是不在使用者電子郵件地址或電話號碼使用 OTP 的情況下,自動確認使用者的高階步驟:

  • 建立 AWS Lambda 函數。
  • 使用預先註冊 Lambda 觸發程式,建立 Amazon Cognito 使用者集區。
  • 在 Amazon Cognito 中註冊使用者。使用 AWS 管理主控台或 AWS API 驗證使用者屬性。

解決方案

請遵循下列步驟,在不使用 OTP 驗證的情況下自動確認使用者。

建立 Lambda 函數

1.    使用 Amazon Cognito Events 建立 Lambda 函數,以處理建立 Amazon Cognito 使用者的事件。下面的 Python 程式碼會確認使用者及其屬性,例如電子郵件地址和電話號碼。

範例 Python 使用者確認碼:

import json

def lambda_handler(event, context):

  # Confirm the user
  event['response']['autoConfirmUser'] = True

  # Set the email as verified if it is in the request
  if 'email' in event['request']['userAttributes']:
    event['response']['autoVerifyEmail'] = True

  # Set the phone number as verified if it is in the request
  if 'phone_number' in event['request']['userAttributes']:
    event['response']['autoVerifyPhone'] = True

  # Return to Amazon Cognito
  return event

2.    使用與預先註冊 Lambda 觸發程式相關的資料,在 Lambda 函數中設定測試事件。下列範例包含步驟 1 中範例 Python 程式碼的測試事件。

範例 JSON 測試事件:

{
  "request": {
    "userAttributes": {
      "email": "email@example.com",
      "phone_number": "5550100"
    }
  },
  "response": {}
}

建立 Amazon Cognito 使用者集區

1.    建立新的 Amazon Cognito 使用者集區,或選取現有的使用者集區。

2.    在選取的使用者集區中,選取您建立的 Lambda 函數,以新增預先註冊 Lambda 觸發程式

預先註冊 Lambda 觸發程式可用於新增自訂邏輯,以及驗證新使用者。當新使用者註冊應用程式時,Amazon Cognito 會將該事件資訊傳遞至 Lambda 函數。(範例 Lambda 函數請參閱 Create a Lambda function (建立 Lambda 函數) 區段的步驟 1。) Lambda 函數會將相同的事件物件傳回至 Amazon Cognito,並在回應中包含任何變更。以下是 Create a Lambda function (建立 Lambda 函數) 區段步驟 2 中測試事件的輸出回應。

範例 JSON 測試事件回應:

{
  "request": {
    "userAttributes": {
      "email": "email@example.com",
      "phone_number": "5550100"
    }
  },
  "response": {
    "autoConfirmUser": true,
    "autoVerifyEmail": true,
    "autoVerifyPhone": true
  }
}

**注意:**如果新使用者透過預先存在的電話號碼或電子郵件地址別名註冊,則別名會移至新使用者。然後,先前使用者的電話號碼或電子郵件地址會標示為未驗證。若要防止這些變更,請呼叫 ListUsers API 以列出使用者集區中所有使用者的屬性。檢閱現有使用者屬性,並將其與新使用者屬性作比較,以確保不會發生非預期的變更。

5.    確認是否已在使用者集區設定預先註冊 Lambda 觸發程式。

註冊 Amazon Cognito 使用者

使用 Amazon Cognito 託管 UI 或叫用 SignUp API,來註冊為新使用者。

使用 Amazon Cognito 託管 UI

1.    在 Amazon Cognito 託管 UI 中,註冊為新使用者。確認提供所有必要的屬性。然後在註冊後,前往 回呼 URL,無需進行任何驗證。

2.    驗證使用者屬性

  • 帳戶狀態:已啟用/已確認
  • email_verified:true
  • phone_number_verified:true

使用 AWS CLI

1.    在 AWS Command Line Interface (AWS CLI) 中,叫用註冊 API 以建立使用者。

**重要事項:**在範例 AWS CLI 命令中,用您的值取代範例字串的所有執行個體。(例如,用您的用戶端 ID 取代 "example_client_id"。)

範例 sign-up 命令:

$ aws cognito-idp sign-up --client-id example_client_id --secret-hash example_secret_hash --username example_user_name --password example_password --user-attributes Name="email",Value="email@example.com" Name="phone_number",Value="5550100"

2.    使用應用程式用戶端 ID、用戶端機密,以及 Amazon Cognito 使用者集區中使用者的使用者名稱,來運算機密雜湊

3.    安裝 Python

4.    將下面的範例 Python 指令碼儲存為 .py 檔案。

重要事項:在執行範例指令碼之前,請先取代下列值。針對 username,請在使用者集區中輸入使用者的使用者名稱。針對 AppClientId,請輸入使用者集區的應用程式用戶端 ID。然後,針對 AppClientSecret,輸入應用程式用戶端機密。如需協助,請執行下列命令:$ python3 secret_hash.py –help

範例 Python 指令碼:

import base64, hashlib, hmac, argparse

parser = argparse.ArgumentParser()
parser.add_argument("--username", required=True)
parser.add_argument("--appclientid", required=True)
parser.add_argument("--appclientsecret", required=True)
args = parser.parse_args()

message = bytes(args.username + args.appclientid, 'utf-8')
key = bytes(args.appclientsecret, 'utf-8')
secret_hash = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()

print('SecretHash: {}'.format(secret_hash))

5.    使用下列命令,從 Python 指令碼取得運算的機密雜湊。

範例命令:

$ python3 secret_hash.py --username example_user_name --appclientid example_app_client_id --appclientsecret example_app_client_secret

自動確認的使用者範例

1.    執行運用使用者名稱、應用程式用戶端 ID 和用戶端機密的 Python 指令碼,以產生機密雜湊。

$ python3 secret_hash.py --username example_user_name --appclientid 11122223333 --appclientsecret je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

輸出:

SecretHash: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

2.    叫用註冊 API,以建立 Amazon Cognito 使用者。

$ aws cognito-idp sign-up --client-id 7morqrabcdEXAMPLE_ID --secret-hash wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY = --username example_user_name --password Password1@ --user-attributes Name='email',Value='email@example.com' Name='phone_number',Value='5550100'

輸出:

{
  "UserConfirmed": true,
  "UserSub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}

3.    若要驗證使用者屬性的狀態,請叫用 AdminGetUser API。

$ aws cognito-idp admin-get-user --user-pool-id us-east-1_I 111122223333 --username example_user_name

輸出:

{
  "Username": "example_user_name",
  "UserAttributes": [
    {
      "Name": "sub",
      "Value": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    },
    {
      "Name": "email_verified",
      "Value": "true"
    },
    {
      "Name": "phone_number_verified",
      "Value": "true"
    },
    {
      "Name": "phone_number",
      "Value": "5550100"
    },
    {
      "Name": "email",
      "Value": "email@example.com"
    }
  ],
  "UserCreateDate": "2022-12-12T11:54:12.988000+00:00",
  "UserLastModifiedDate": "2022-12-12T11:54:12.988000+00:00",
  "Enabled": true,
  "UserStatus": "CONFIRMED"
}

最終輸出會顯示電子郵件地址和電話號碼屬性已驗證。UserStatus 設定為 Confirmed (已確認),無需任何外部驗證。


AWS 官方
AWS 官方已更新 1 年前