如何在 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 事件创建 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 函数位于“创建 Lambda 函数”部分的步骤 1 中。) Lambda 函数会将相同的事件对象返回给 Amazon Cognito,同时在响应中包括任何更改。以下是“创建 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.    验证您的用户属性

  • 账户状态:Enabled/CONFIRMED(已启用/已确认)
  • email_verified:true
  • phone_number_verified:true

使用 AWS CLI

1.    在 AWS 命令行界面 (AWS CLI) 中,通过调用 SignUp API 创建用户。

**重要提示:在示例 AWS CLI 命令中,请将示例字符串的所有实例替换为您的值。(例如,将“example_client_id”**替换为您的客户端 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.    通过调用 SignUp 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 年前