13

AWS 文档表明管理员可以使用 API 在 AWS Cognito 中创建用户池用户。

这是我指的文档:https ://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html

但是,文档提供的细节很少,甚至没有提供如何完成的示例。它没有提及调用什么端点、使用什么 SDK 功能或任何有关身份验证的内容等。

有没有人有直接从您的代码创建新用户的经验?

4

2 回答 2

15

如果您遵循开发文档(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部分中(通常电子邮件默认为 required,检查您的是否是)。您可以为其赋值的事物列表位于(Cognito pool) General Settings -> App Clients -> Show Details -> Set Read/Write -> (list of things)中,您可以在此处添加自定义属性(例如,如果您想要指定您的用户来自哪个城市,或者您是否想要添加其他任何内容(字符串/数字)。

为自定义字段分配值时,您在 UserAttributes 中的“名称”将为“custom:whatever”,因此如果自定义字段为“city”,则名称为“custom:city”。

希望我没有说太多显而易见的事情,但这些是我花了一段时间才弄明白的分解的 SO 信息和 AWS 文档,我想我会把它们放在一起。

于 2019-02-07T20:01:53.363 回答
6

这是一个使用 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)
于 2018-05-16T20:58:38.047 回答