如何通过编程在Cognito用户池中创建用户?

16
2个回答

21

如果你遵循开发文档(https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html),特别是"signUp"函数,那么这其实非常简单。

文档上写道:

var params = {
  ClientId: 'STRING_VALUE', /* required */
  Password: 'STRING_VALUE', /* required */
  Username: 'STRING_VALUE', /* required */
  AnalyticsMetadata: {
    AnalyticsEndpointId: 'STRING_VALUE'
  },
  SecretHash: 'STRING_VALUE',
  UserAttributes: [
    {
      Name: 'STRING_VALUE', /* required */
      Value: 'STRING_VALUE'
    },
    /* more items */
  ],
  UserContextData: {
    EncodedData: 'STRING_VALUE'
  },
  ValidationData: [
    {
      Name: 'STRING_VALUE', /* required */
      Value: 'STRING_VALUE'
    },
    /* more items */
  ]
};
cognitoidentityserviceprovider.signUp(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

使用这个功能,创建用户非常简单(以下是Lambda示例,但可以轻松修改为JS):

'use strict'
var AWS = require('aws-sdk');
var resp200ok = { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: {} };
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
// ^ Hard to find that this is the way to import the library, but it was obvious in docs

exports.handler = function(event, context, callback){
    var params = {
        ClientId: 'the App Client you set up with your identity pool (usually 26 alphanum chars)',
        Password: 'the password you want the user to have (keep in mind the password restrictions you set when creating pool)',
        Username: 'the username you want the user to have',
        UserAttributes:[ {
            {
                Name: 'name', 
                Value: 'Private'
            }, 
            {
                Name: 'family_name', 
                Value: 'Not-Tellinglol'
            },
        }],
    };

    cognitoidentityserviceprovider.signUp(params, function(err, data) {
        if (err){ console.log(err, err.stack); }
        else{ resp200ok.body = JSON.stringify(data); callback(null, resp200ok); }
    });
};

在 Cognito 池设置中将任何内容设置为 required,都必须在UserAttributes部分中(通常电子邮件默认为必填,检查您的是否是)。您可以在 (Cognito池)通用设置->应用程序客户端->显示详情->设置读/写->(属性列表) 中找到可分配值的项目列表,在此处您可以添加自定义属性(例如,如果您想指定用户来自哪个城市,或者添加其他任何内容(字符串/数字))。

将值分配给自定义字段时,UserAttributes 中的 "Name" 将是 "custom:whatever",因此,如果自定义字段是 "city",则名称为 "custom:city"。

希望我没有讲太多显而易见的事情,但这些是我通过断断续续的 SO 信息和 AWS 文档花费了一段时间才弄清楚的内容,我想把它们总结在一起。


2
同时也作为默认可用属性列表非常有用:https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html - T1960CT

8
这是一个使用Python/Flask的示例。
import traceback
import boto3
from flask import Flask, render_template, request

app = Flask(__name__)


def cognito_register_user(email):
    print("sign up user: ", email)

    try:
        aws_client = boto3.client('cognito-idp', region_name = "us-west-2",)
        response = aws_client.admin_create_user(UserPoolId="us-west-2_sdfgsdfgsdfg",Username=email,UserAttributes=[{"Name": "email","Value": email},{ "Name": "email_verified", "Value": "true" }],DesiredDeliveryMediums=['EMAIL'])
        print("response=", response)
        return response
    except:
        traceback.print_exc()
    return None


@app.route('/')
def root():
    return render_template('register_email.html', title='register mail')


@app.route('/register/email', methods=['POST'])
def sign_up():
    if request.method == 'POST':
        email = request.form['email']
        print("email=", email)
        cognito_register_user(email)
    return render_template('register_email_complete.html', title='flask test', email=email)


if __name__ == "__main__":
    app.run(debug=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接