如何以编程方式在Cognito用户池中创建用户?

时间:2018-01-18 18:00:08

标签: javascript amazon-web-services amazon-cognito aws-sdk-js

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

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

然而,文档提供的细节很少,甚至没有提供如何完成的示例。它没有提到要调用的端点,要使用的SDK功能,或者有关身份验证的任何内容等。

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

2 个答案:

答案 0 :(得分:2)

如果您遵循开发文档(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池设置中设置为必需的所有内容都必须位于 UserAttributes 部分(通常,电子邮件默认为必填,请检查您的电子邮件是否为必填项)。您可以在(认知池)“常规设置”->“应用程序客户端”->“显示详细信息”->“设置读/写”->(事物列表)中找到可以为其分配值的事物列表,在这里您可以添加自定义属性(例如,如果您想指定用户来自哪个城市,或者是否要添加其他内容(字符串/数字))。

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

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

答案 1 :(得分:1)

以下是使用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)
相关问题