0. cognito的认证流程
1. 配置cognito
创建用户池, 使用命令行创建和激活用户,.getIdToken().getJwtToken() 获取jwt
## 创建用户
aws cognito-idp sign-up --client-id $AppClientId --username student --password student
## 确认创建用户
aws cognito-idp admin-confirm-sign-up --user-pool-id $CognitoPoolId --username student
region=$(curl http://169.254.169.254/latest/meta-data/placement/region -s)
acct=$(aws sts get-caller-identity --output text --query "Account")
poolId=$(aws cognito-idp list-user-pools --max-results 1 --output text --query "UserPools[].Id")
poolArn="arn:aws:cognito-idp:$region:$acct:userpool/$poolId"
与apigateway集成
## 获取apigateway id
apiId=$(aws apigateway get-rest-apis --query "items[?name == 'PollyNotesAPI'].id" --output text)
## 导入swagger
aws apigateway put-rest-api --rest-api-id $apiId --mode merge --body 'fileb://PollyNotesAPI-swagger.yaml'
## 部署apigateway
aws apigateway create-deployment --rest-api-id $apiId --stage-name Prod
## 添加lambda权限
aws lambda add-permission --function-name delete-function --statement-id apiInvoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com
与应用程序集成
## 获取S3代码
webBucket=$(aws s3api list-buckets --output text --query 'Buckets[?contains(Name, `pollynotesweb`) == `true`].Name')
前端集成代码
import {
CognitoUserPool,
CognitoUser,
AuthenticationDetails } from 'amazon-cognito-identity-js';
const poolData = {
UserPoolId: us-east-1_O4qztJARR,
AppClientId: 21cfp6vimec5orctf289nhb03p
}
const UserPool = new CognitoUserPool(poolData);
const user = new CognitoUser({
Username: student,
Pool: UserPool
})
const authDetails = new AuthenticationDetails({
Username: student,
Password: student
})
user.authenticateUser(authDetails, {
onSuccess: data => {
console.log('Success:', data)
setToken(data.getIdToken().getJwtToken())
},
onFailure: err => {
console.error('Failure:', err)
},
newPasswordRequired: data => {
console.log('newPasswordRequired:', data)
}
})
打印的是如下结果:
Amazon Cognito 托管的 UI 不支持自定义身份验证流程。
使用 Amazon Cognito 托管 UI 进行注册和登录 - Amazon Cognito
Control access to a REST API using Amazon Cognito user pools as authorizer - Amazon API Gateway
认证授权专题(四) : 利用Cognito Group信息管理多套API Gateway+lambda环境 | 亚马逊AWS官方博客