如何使用AWS CDK创建AWS Cognito堆栈

huangapple go评论89阅读模式
英文:

How to create AWS Cognito stack using AWS CDK

问题

以下是您提供的代码的翻译部分:

  1. I'm new to aws cloudformation and the cdk. I'm trying to create a sample stack just to try things out and I keep getting this error: "Invalid Cognito Identity Provider (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidParameterException; Request ID: 7db28b4b-373b-4808-9c8d-1d197b0be542; Proxy: null)"
  2. My code:
  3. // 以下是您的代码,包括各个部分的创建和配置
  4. // ...
  5. module.exports = { MyCdkStack }
  6. // const app = new cdk.App();
  7. // new MyStack(app, 'MyStack');

希望这对您有所帮助,如果您有任何其他问题或需要进一步的帮助,请随时告诉我。

英文:

I'm new to aws cloudformation and the cdk. I'm trying to create a sample stack just to try things out and I keep getting this error: "Invalid Cognito Identity Provider (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: InvalidParameterException; Request ID: 7db28b4b-373b-4808-9c8d-1d197b0be542; Proxy: null)"

My code:

  1. const cdk = require('aws-cdk-lib');
  2. const ec2 = require('aws-cdk-lib/aws-ec2');
  3. const apigateway = require('aws-cdk-lib/aws-apigateway');
  4. const cognito = require('aws-cdk-lib/aws-cognito');
  5. const iam = require('aws-cdk-lib/aws-iam');
  6. const { Stack } = require('aws-cdk-lib');
  7. class MyCdkStack extends Stack {
  8. /**
  9. *
  10. * @param {Construct} scope
  11. * @param {string} id
  12. * @param {StackProps=} props
  13. */
  14. constructor(scope, id, props) {
  15. super(scope, id, props);
  16. // Create a VPC for the EC2 instance
  17. const vpc = new ec2.Vpc(this, 'MyVPC', {
  18. maxAzs: 2 // Use 2 availability zones
  19. });
  20. const sg = new ec2.SecurityGroup(this, 'MySSHSecurityGroup', {
  21. vpc,
  22. description: 'Allow Outbound SSH access',
  23. securityGroupName: 'My SSH Security Group',
  24. allowAllOutbound: true // Allow all outbound traffic
  25. });
  26. // Allow SSH access from a specific IP range
  27. sg.addIngressRule(ec2.Peer.ipv4('anipaddress/32'), ec2.Port.tcp(22), 'Allow inbound SSH access from here');
  28. sg.addIngressRule(ec2.Peer.ipv4('anipaddress/32'), ec2.Port.tcp(22), 'Allow inbound SSH access from here 2');
  29. /////////////////////
  30. // Create a Cognito user pool
  31. const userPool = new cognito.UserPool(this, 'MyUserPool', {
  32. userPoolName: 'My User Pool',
  33. selfSignUpEnabled: true,
  34. autoVerify: { email: true },
  35. signInAliases: { email: true },
  36. passwordPolicy: {
  37. minLength: 8,
  38. requireDigits: true,
  39. requireLowercase: true,
  40. requireUppercase: true,
  41. requireSymbols: true
  42. }
  43. });
  44. const userPoolClient = new cognito.CfnUserPoolClient(this, "MyUserPoolClient", {
  45. userPoolId: userPool.ref,
  46. explicitAuthFlows: ["ADMIN_NO_SRP_AUTH"],
  47. generateSecret: false,
  48. readAttributes: [
  49. "preferred_username",
  50. "website",
  51. "email",
  52. "name",
  53. "zoneinfo",
  54. "phone_number",
  55. "phone_number_verified",
  56. "email_verified",
  57. ],
  58. writeAttributes: ["name", "zoneinfo", "phone_number"],
  59. });
  60. // Create a Cognito identity pool
  61. const identityPool = new cognito.CfnIdentityPool(this, 'MyIdentityPool', {
  62. identityPoolName: 'My Identity Pool',
  63. allowUnauthenticatedIdentities: false,
  64. cognitoIdentityProviders: [{
  65. clientId: userPoolClient.ref,
  66. providerName: userPool.userPoolProviderName,
  67. }]
  68. });
  69. // Create an API Gateway REST API
  70. const restApi = new apigateway.RestApi(this, 'MyRestApi', {
  71. restApiName: 'My Rest API',
  72. deployOptions: {
  73. stageName: 'prod'
  74. }
  75. });
  76. const sg2 = new ec2.SecurityGroup(this, 'MyAPIGatewaySecurityGroup', {
  77. vpc,
  78. description: 'Allow port 80 traffic from the API Gateway',
  79. securityGroupName: 'My API Gateway Security Group',
  80. allowAllOutbound: true // Allow all outbound traffic
  81. });
  82. // Allow port 80 traffic from the API Gateway
  83. sg2.addIngressRule(
  84. ec2.Peer.ipv4(`${restApi.restApiId}.execute-api.${cdk.Stack.of(this).region}.amazonaws.com/32`),
  85. ec2.Port.tcp(80),
  86. 'Allow port 80 traffic from the API Gateway'
  87. );
  88. const keyName = 'my-key-pair';
  89. // Create an EC2 key pair for SSH access
  90. const key = new ec2.CfnKeyPair(this, 'MyKeyPair', {
  91. keyName,
  92. });
  93. // Associate the key pair with the EC2 instance
  94. const instance = new ec2.Instance(this, 'MyEC2Instance', {
  95. instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
  96. machineImage: new ec2.AmazonLinuxImage(),
  97. vpc,
  98. securityGroup: sg2,
  99. key,
  100. userData: ec2.UserData.custom(`
  101. #!/bin/bash
  102. echo "Hello, world!" > /var/www/html/index.html
  103. `)
  104. });
  105. // Create a Cognito authorizer
  106. const authorizer = new apigateway.CfnAuthorizer(this, 'MyCognitoAuthorizer', {
  107. name: 'My-Cognito-Authorizer',
  108. identitySource: 'method.request.header.Authorization',
  109. restApiId: restApi.restApiId,
  110. type: apigateway.AuthorizationType.COGNITO,
  111. providerArns: [userPool.userPoolArn]
  112. });
  113. // Create a resource and method for the API Gateway and Add the Cognito authorizer to the method
  114. const resource = restApi.root.addResource('my-resource');
  115. const method = resource.addMethod('GET', new apigateway.HttpIntegration(`http://${instance.instancePublicIp}`),
  116. {
  117. authorizationType: apigateway.AuthorizationType.COGNITO, authorizer: authorizer
  118. });
  119. // Create an IAM role for authenticated users
  120. const authenticatedRole = new iam.Role(this, 'MyAuthenticatedRole', {
  121. assumedBy: new iam.FederatedPrincipal('cognito-identity.amazonaws.com', {
  122. StringEquals: { 'cognito-identity.amazonaws.com:aud': identityPool.ref },
  123. 'ForAnyValue:StringLike': { 'cognito-identity.amazonaws.com:amr': 'authenticated' }
  124. }, 'sts:AssumeRoleWithWebIdentity')
  125. });
  126. // Create an IAM role for unauthenticated users
  127. const unauthenticatedRole = new iam.Role(this, 'MyUnauthenticatedRole', {
  128. assumedBy: new iam.FederatedPrincipal('cognito-identity.amazonaws.com', {
  129. StringEquals: { 'cognito-identity.amazonaws.com:aud': identityPool.ref },
  130. 'ForAnyValue:StringLike': { 'cognito-identity.amazonaws.com:amr': 'unauthenticated' }
  131. }, 'sts:AssumeRoleWithWebIdentity')
  132. });
  133. // Grant permissions to the authenticated role
  134. authenticatedRole.addToPolicy(new iam.PolicyStatement({
  135. effect: iam.Effect.ALLOW,
  136. actions: [
  137. 'execute-api:Invoke'
  138. ],
  139. resources: [
  140. method.methodArn
  141. ]
  142. }));
  143. // Grant permissions to the unauthenticated role
  144. unauthenticatedRole.addToPolicy(new iam.PolicyStatement({
  145. effect: iam.Effect.ALLOW,
  146. actions: [
  147. 'cognito-identity:GetId',
  148. 'cognito-identity:GetOpenIdToken'
  149. ],
  150. resources: [
  151. `arn:aws:cognito-identity:${this.region}:${this.account}:identitypool/${identityPool.ref}`
  152. ]
  153. }));
  154. // Set the roles for authenticated and unauthenticated users
  155. new cognito.CfnIdentityPoolRoleAttachment(this, 'MyIdentityPoolRoles', {
  156. identityPoolId: identityPool.ref,
  157. roles: {
  158. authenticated: authenticatedRole.roleArn,
  159. unauthenticated: unauthenticatedRole.roleArn
  160. }
  161. });
  162. }
  163. }
  164. module.exports = { MyCdkStack }
  165. // const app = new cdk.App();
  166. // new MyStack(app, 'MyStack');

EDIT (Added screenshot):如何使用AWS CDK创建AWS Cognito堆栈

答案1

得分: 1

以下是翻译好的部分:

  1. // 使用一个更加现代的示例。也许是这样的:
  2. const userPoolWebClient = new cognito.UserPoolClient(
  3. this,
  4. 'userPoolWebClient',
  5. {
  6. userPool: userPool,
  7. generateSecret: false,
  8. preventUserExistenceErrors: true,
  9. authFlows: {
  10. userPassword: true,
  11. userSrp: true,
  12. },
  13. oAuth: {
  14. flows: {
  15. authorizationCodeGrant: false,
  16. implicitCodeGrant: true,
  17. },
  18. },
  19. },
  20. );
  21. new core.CfnOutput(this, 'UserPoolWebClientId', {
  22. value: userPoolWebClient.userPoolClientId,
  23. });
  24. const identityPool = new cognito.CfnIdentityPool(
  25. this,
  26. 'DashboardIdentityPool',
  27. {
  28. cognitoIdentityProviders: [
  29. {
  30. clientId: userPoolWebClient.userPoolClientId,
  31. providerName: `cognito-idp.${this.region}.amazonaws.com/${userPool.userPoolId}`,
  32. },
  33. ],
  34. allowUnauthenticatedIdentities: true,
  35. },
  36. );
英文:

Use a more up-to-date example. Perhaps:

  1. const userPoolWebClient = new cognito.UserPoolClient(
  2. this,
  3. 'userPoolWebClient',
  4. {
  5. userPool: userPool,
  6. generateSecret: false,
  7. preventUserExistenceErrors: true,
  8. authFlows: {
  9. userPassword: true,
  10. userSrp: true,
  11. },
  12. oAuth: {
  13. flows: {
  14. authorizationCodeGrant: false,
  15. implicitCodeGrant: true,
  16. },
  17. },
  18. },
  19. );
  20. new core.CfnOutput(this, 'UserPoolWebClientId', {
  21. value: userPoolWebClient.userPoolClientId,
  22. });
  23. const identityPool = new cognito.CfnIdentityPool(
  24. this,
  25. 'DashboardIdentityPool',
  26. {
  27. cognitoIdentityProviders: [
  28. {
  29. clientId: userPoolWebClient.userPoolClientId,
  30. providerName: `cognito-idp.${this.region}.amazonaws.com/${userPool.userPoolId}`,
  31. },
  32. ],
  33. allowUnauthenticatedIdentities: true,
  34. },
  35. );

huangapple
  • 本文由 发表于 2023年2月24日 02:31:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定