APIGateWay 生成Post请求通过Lambda操作Cognito
目标:生成Restful接口,可以通过PostMan直接发送Post请求,返回Json格式用户信息
A.查询用户信息【getinfo】
Postman请求参数【选择Post方法、通过Body传参、参数格式Raw、Json】
{
"username":"joe"
}
Lambda请求参数【注意要转成Json字符串,且不能换行】
{
"body": "{\"username\":\"joe\"}"
}
Curl请求参数【粘贴到命令栏即可调试】
curl --location --request POST 'https://vfv2ngwevb.execute-api.eu-north-1.amazonaws.com/dev/getinfo' \
--header 'Content-Type: application/json' \
--data-raw '{
"username":"joe"
}'
AWS响应
{
"sub": "d41b744e-1751-4122-98b3-6568e49b376c",
"email_verified": "true",
"custom:company_name": "Wanke",
"custom:position": "CFO",
"preferred_username": "Ace",
"email": "11213213213123121@163.com",
"custom:salary": "888888"
}
请求代码【Lambda代码】
const AWS = require('aws-sdk');
exports.handler = async (event, context, callback) => {
const cognito = new AWS.CognitoIdentityServiceProvider();
const body = event['body'];
const obj = JSON.parse(body);
//析构函数
const { username } = obj;
var params = {
UserPoolId: 'xxxxx',
Username: username,
};
const res = await cognito.adminGetUser(params).promise()
console.log(res);
const {UserAttributes} = res
const resMap = new Map()
UserAttributes.forEach((dict)=>{
const {Name, Value} = dict;
resMap.set(Name, Value);
});
///Json
const json = Object.fromEntries(resMap);
///Json
const str = JSON.stringify(json);
console.log(typeof(resMap) + typeof(json) + typeof(str));
var testRes ={
"statusCode": 200,
"body":str
};
return callback(null,testRes);
};
B.修改用户信息【updateinfo】
Postman请求参数【选择Post方法、通过Body传参、参数格式Raw、Json】
{
"username": "joe",
"custom:position": "CFO",
"custom:company_name": "Wanke",
"custom:salary": "888888",
"preferred_username": "Ace",
"email":"11213213213123121@163.com",
"email_verified": "true"
}
Lambda请求参数【注意要转成Json字符串,且不能换行】
{
"body": "{\"username\": \"joe\",\"custom:position\": \"UFO\",\"email\": \"999999@163.com\",\"email_verified\": \"true\"}"
}
Curl请求参数【粘贴到命令栏即可调试】
curl --location --request POST 'https://vfv2ngwevb.execute-api.eu-north-1.amazonaws.com/dev/updateinfo' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "joe",
"custom:position": "CFO",
"custom:company_name": "Wanke",
"custom:salary": "888888",
"preferred_username": "Ace",
"email":"11213213213123121@163.com",
"email_verified": "true"
}'
AWS响应
Success
请求代码【Lambda代码】
const AWS = require('aws-sdk');
exports.handler = async (event, context, callback) => {
const cognito = new AWS.CognitoIdentityServiceProvider();
const body = event['body'];
console.log("event type:" + typeof(body));
console.log("body type:" + typeof(body));
const obj = JSON.parse(body);
console.log("obj type:" + typeof(obj));
//析构函数
const {username} = obj;
console.log("username:"+username);
var resultStatusCode = '200';
var resultString;
var updateArr = new Array();
for(var key in obj){
console.log(key);
console.log(obj[key]);
if(key != 'username'){
///一定要是Object , 不能是Json
var updateObject = {Name:key,Value:obj[key]};
updateArr.push(updateObject);
}
}
console.log(updateArr);
const params = {
UserAttributes: updateArr,
UserPoolId: 'xxxxxxx',
Username: username
};
await cognito.adminUpdateUserAttributes(params,function(err,data){
if (err) {
console.log("Error", err);
resultStatusCode = '500';
resultString = "Error";
} else {
console.log("Success", data);
resultStatusCode = '200';
resultString = "Success";
}
}).promise();
var res ={
"statusCode": resultStatusCode,
"body":resultString
};
callback(null,res);
};
API GateWay设置
1.打开API Gateway 点击Create API
2.在REST API 选择 Build
3.下一个页面保持默认选择,输入API name创建即可
4.Actions=》Create Resource=>打钩 Enable API Gateway CORS
5.选中刚刚创建的Resource=》Actions=》Create Method=>选择Post方法
6.Integration type:Lambda Function,Use Lambda Proxy integration打钩,选择对应的Lambda Region、Lambda Function
7.Actions=》Deploy API=>配置好Stage
Q1. 如何解决AccessDeniedException【is not authorized to perform】
解决方法:
A.在Lambda函数页面,选择Configuration=>Permissions=>Execution role
B.Policy name确保有全部Cognito的权限:
Q2.发送的Post请求 如何Debug
1.在Labmda页面打开需要Debug的Function
2.在代码中加上Console.log
3.Monitor=>View CloudWatch logs查看日志
Q3.通过APIGateway接受的Post请求 标准返回样式
exports.handler = async (event) => {
var res ={
"statusCode": 200,
"body":"此处一定是字符串"
};
return res;
};
"statusCode": 200,不可少否则
{"message": "Internal server error"}
网友评论