[英]How can you programmatically create a user in a Cognito User Pool?
AWS文檔表明管理員可以使用API在AWS Cognito中創建用戶池用戶。
以下是我所指的文檔: https : //docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html
但是,文檔提供的細節很少,甚至沒有提供如何完成的示例。 它沒有提到要調用的端點,要使用的SDK函數或有關身份驗證的任何內容等。
有沒有人有直接從您的代碼創建新用戶的經驗?
如果您遵循開發文檔( https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html ),更具體地說是“signUp”功能,這實際上非常簡單。
來自Docs:
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部分中(通常,該電子郵件默認為必需,請檢查您的是否是)。 可以在(Cognito池)常規設置 - >應用程序客戶端 - >顯示詳細信息 - >設置讀/寫 - >(事物列表)中找到可以分配值的事項列表 ,在這里您可以添加自定義屬性(如果您想要指定您的用戶所在的城市,或者您是否要添加其他任何城市(字符串/數字))。
將值分配給自定義字段時,UserAttributes中的“名稱”將為“custom:whatever”,因此,如果自定義字段為“city”,則“名稱”為“custom:city”。
希望我沒有說太多顯而易見的事情,但這些事情花了我一段時間來弄清楚SO信息和AWS文檔,我想我會把它全部放在一起。
這是一個使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.