来自java脚本SDK的AWS Cognito adminCreateUser

时间:2017-02-15 09:23:18

标签: javascript amazon-cognito

我尝试从AWS Lambda 创建AWS用户池中的用户

我尝试使用这个脚本从似乎是AWS的官方JavascriptSDK获取,但无法使其正常工作。 http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminCreateUser-property

我一直收到此错误:ypeError:cognitoidentityserviceprovider.adminCreateUser不是函数

var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

var params = {
    UserPoolId: 'eu-west-1_XXXXXXXX', /* required */
    Username: 'me@example.com', /* required */
    DesiredDeliveryMediums: [
        'EMAIL'
    ],
    ForceAliasCreation: false,
    MessageAction: 'SUPPRESS',
    TemporaryPassword: 'tempPassword1',
    UserAttributes: [
        {
            Name: 'email', /* required */
            Value: 'me@example.com'
        },
        {
            Name: 'name', /* required */
            Value: 'Me'
        },
        {
            Name: 'last_name', /* required */
            Value: 'lastme'
        }
        /* more items */
    ]
};
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
    callback(null, data);
});

4 个答案:

答案 0 :(得分:3)

对于adminCreateUser(您基本上需要aws sdk,配置凭据,实例化客户端并调用特定操作)。

var aws = require('aws-sdk');
aws.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});

var CognitoIdentityServiceProvider = aws.CognitoIdentityServiceProvider;
var client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19
//your code here

请注意,您可以通过不同的方式配置AWS凭据以调用该操作。您确实需要凭据,因为这是经过身份验证的操作。其他管理操作类似,您只需要在调用中将相应的参数作为JSON传递。

根据这一点,AWS SDK for JavaScript版本2.7.25应包含adminCreateUser操作。

http://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html

答案 1 :(得分:1)

关于成功创建用户。检查控制台上的消息

enter image description here

创建用户失败。检查控制台上的消息

enter image description here

var AWS = require('aws-sdk');


var cognitoidentityserviceprovider = new 

AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

let response;

exports.handler = async function(event, context, callback){
const attributes = event.request.userAttributes;  // read user attributes from event
console.log('User Role : ',attributes['custom:role'])
var params = {
    UserPoolId:'YOUR POOL ID',
    Username: attributes.email,
    //TemporaryPassword: 'Password!1',
    DesiredDeliveryMediums: ["EMAIL"],
    UserAttributes: [
      { 
            Name: "email",
            Value: attributes.email
      },
      {
            Name: 'email_verified', /* required */
            Value: 'true'
      },
      {
            Name: 'custom:name', /* required */
            Value: attributes['custom:name']
      },
      {
            Name: 'custom:role', /* required */
            Value: attributes['custom:role']
      },
    ],
 };

await createUser(params);
return response;

};

async function createUser(params) {
// body...
await new Promise((resolve, reject) => {
    
       cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
      if (err) 
      {
          console.log("FAILED ",err, err.stack); // an error occurred
          response={statusCode:500, body:{message:"FAILED", error:err}}
          reject();
      }
      else 
      {
          console.log('SUCCESS', data);// successful response
          response={statusCode:200, body:{message:"SUCCESS"}}
          resolve();
      }
});
    
});
}

答案 2 :(得分:1)

Test case for Lambda Function in AWS

用于创建用户的 Lambda 函数

var AWS = require('aws-sdk');

var cognitoidentityserviceprovider = new 
AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

let response;
exports.handler = async function(event, context, callback){
const attributes = event.request.userAttributes;  // read user attributes from event
console.log('User Role : ',attributes['custom:role'])
var params = {
    UserPoolId:'YOUR POOL ID',
    Username: attributes.email,
    //TemporaryPassword: 'Password!1',
    DesiredDeliveryMediums: ["EMAIL"],
    UserAttributes: [
      { 
            Name: "email",
            Value: attributes.email
      },
      {
            Name: 'email_verified', /* required */
            Value: 'true'
      },
      {
            Name: 'custom:name', /* required */
            Value: attributes['custom:name']
      },
      {
            Name: 'custom:role', /* required */
            Value: attributes['custom:role']
      },
    ],
};

await createUser(params);
return response;

};

async function createUser(params) {
// body...
try {
const data = await cognitoidentityserviceprovider.adminCreateUser(params).promise();
response={statusCode:200, body:{message:"SUCCESS"}}
} 
catch (error) 
{
console.log(error);
response={statusCode:500, body:{message:"FAILED", error:error}}
}

}

创建新用户时的响应 enter image description here

如果用户已存在于认知用户池中的响应

Response if User Already exists in cognito user pool

enter image description here React JS 中用于创建用户的前端代码

import React from "react";
import TextField from "@material-ui/core/TextField";
import Container from "@material-ui/core/Container";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import { ADD_USER } from "../../Constants/PathConstants";
import { useState } from "react";
import SnackbarMessage from '../SnackbarMessage'


//style for the component
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));

function AddUsers() {

const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [addrtype, setAddrtype] = useState(["Normal", "Admin"])
const Add = addrtype.map(Add => Add)
const handleAddrTypeChange = (e) => { console.clear(); 
console.log((addrtype[e.target.value])); setRole(addrtype[e.target.value]) }
const [role, setRole] = useState('Normal')
// usage of the above component
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [snackbarMessage, setSnackbarMessage] = useState("");
const [snackbarSeverity, setSnackbarSeverity] = useState("");
const classes = useStyles();

const handleAddUser = async (event) => {
event.preventDefault();
console.log(`
  Name: ${name}
  Email: ${email} 
  Role: ${role}           
`);

var axios = require("axios");
var data = JSON.stringify({
  request: {
    userAttributes: {
      "custom:name": name,
      email: email,
      "custom:role": role,
    },
  },
  response: {}
});

var config = {
  method: "post",
  url: "YOUR URL to API Gateway -> Lambda function"
    
  headers: {
    "Content-Type": "application/json",
  },
  data: data,
};

let res = await axios(config)
console.log(res);
let statusCode = res.data.statusCode;
if (statusCode === 200) {
  console.log(res.data.statusCode);
  setSnackbarMessage("User Created Succesfully");
  setSnackbarSeverity("success");
  setSnackbarOpen(true);
} else if (statusCode === 500) {
  console.log(res.data.statusCode);
  console.log(res.data.body.error.message);
  let err_Msg = res.data.body.error.message;
  setSnackbarMessage(err_Msg);
  setSnackbarSeverity("error");
  setSnackbarOpen(true);
}

};

return (
<Container component="main" maxWidth="xs">
  <div className={classes.paper}>
    {/* Header for the component */}
    <Typography component="h1" variant="h5">
      {ADD_USER}
    </Typography>
    {/* Content for the component */}
    <form className={classes.form} onSubmit={handleAddUser}>
      <TextField
        id="outlined-basic"
        label="Full Name"
        variant="outlined"
        margin="normal"
        fullWidth
        value={name}
        placeholder="Name"
        required
        onChange={(event) => setName(event.target.value)}
      />
      <TextField
        fullWidth
        margin="normal"
        id="outlined-basic"
        label="Email Id"
        variant="outlined"
        value={email}
        placeholder="Email"
        required
        onChange={(event) => setEmail(event.target.value)}
      />
      <label for="role">Choose a Role:</label>
      < select
        onChange={e => handleAddrTypeChange(e)}
        className="browser-default custom-select" >
        {
          Add.map((address, key) => <option key={key} value={key}>{address}</option>)
        }
      </select >
      <Button
        type="Upload"
        fullWidth
        variant="contained"
        color="primary"
        className={classes.submit}
      >
        {ADD_USER}
      </Button>
    </form>
  </div>
  <SnackbarMessage message={snackbarMessage} open={snackbarOpen} setopen= 
{setSnackbarOpen} severity={snackbarSeverity} />
</Container>
);
}
export default AddUsers;

答案 3 :(得分:0)

尝试将最新的aws-sdk捆绑到您上传的软件包中,而不是依赖于默认情况下可用的aws-sdk。

来源:AWS Cognito adminCreateUser from Lambda