微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法将注册用户添加到 AWS 中的 AdminGroup

如何解决无法将注册用户添加到 AWS 中的 AdminGroup

我无法使用 Serverless 将用户添加到 AdminGroup,请找到我的代码

请找到我的无服务器模板

service: sls-cognito-12

provider:
  name: aws
  runtime: nodejs12.x
  region: ca-central-1
custom:
  settings:
    POSTS_TABLE: jintoTbl-tblDepartment456
functions:
  UserOnboardingLambda:
    handler: handler.createPost
    events:
      - cognitoUserPool:
          pool: cognito_sls_backend_user_pools
          trigger: PostConfirmation
          existing: true
    role: CustomUserOnboardingRole
    environment:
      TABLE_NAME: ${self:custom.settings.POSTS_TABLE}
      REGION: ca-central-1

resources:
  Resources:
    # Cognito - User pool
    CognitoUserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: cognito_sls_backend_user_pools
        Policies:
          PasswordPolicy:
            MinimumLength: 8
            RequireLowercase: true
            RequireUppercase: true
            RequireNumbers: true
            RequireSymbols: true
        UsernameAttributes:
          - email
        Schema:
        - Name: name
          AttributeDataType: String
          Mutable: true
          required: true
        - Name: email
          AttributeDataType: String
          Mutable: false
          required: true
        - Name: phone_number
          AttributeDataType: String
          Mutable: false
          required: true      
        AutoVerifiedAttributes:
        - email        
    # Cognito - Client
    CognitoUserPoolClient:
      Type: AWS::Cognito::UserPoolClient
      Properties:
        ClientName: cognito_sls_backend_client
        UserPoolId:
          Ref: CognitoUserPool
        SupportedIdentityProviders:
          - COGNITO
        CallbackURLs: ['https://www.google.com']
        logoutURLs: ['https://www.google.com']
        AllowedOAuthFlowsUserPoolClient: true
        AllowedOAuthFlows:
          - code
          - implicit
        AllowedOAuthScopes:
          - openid
          - email
          - phone
          - profile
          - aws.cognito.signin.user.admin
        
    # Cognito - Identity
    CognitoIdentityPool:
      Type: AWS::Cognito::IdentityPool
      Properties:
        IdentityPoolName: cognito_sls_backend_identity_pool
        AllowUnauthenticatedIdentities: false
        CognitoIdentityProviders:
          - ClientId:
              Ref: CognitoUserPoolClient
            ProviderName:
              Fn::GetAtt: [CognitoUserPool,ProviderName]
    CognitoUserPoolDomain:
      Type: AWS::Cognito::UserPoolDomain
      Properties:
        Domain: jintodomain # what is before .auth.REGION.amazoncognito.com
        UserPoolId:
          Ref: CognitoUserPool # given the name of your resource
    # Cognito roles
    CognitoIdentityPoolRoles:
      Type: AWS::Cognito::IdentityPoolRoleAttachment
      Properties:
        IdentityPoolId:
          Ref: CognitoIdentityPool
        Roles:
          authenticated:
            Fn::GetAtt: [CognitoAuthRole,Arn]
          unauthenticated:
            Fn::GetAtt: [CognitoUnauthRole,Arn]
    CognitoAuthRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: appauthRoleJinto121111
        Path: /
        AssumeRolePolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Principal:
                Federated: "cognito-identity.amazonaws.com"
              Action:
                - "sts:AssumeRoleWithWebIdentity"
              Condition:
                StringEquals:
                  "cognito-identity.amazonaws.com:aud":
                    Ref: CognitoIdentityPool
                "ForAnyValue:StringLike":
                  "cognito-identity.amazonaws.com:amr": authenticated
        Policies:
          - PolicyName: "CognitoAuthorizedPolicy"
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: "Allow"
                  Action:
                    - "mobileanalytics:PutEvents"
                    - "cognito-sync:*"
                    - "cognito-identity:*"
                  Resource: "*"
                - Effect: "Allow"
                  Action:
                    - "execute-api:Invoke"
                  Resource: "*"
    CognitoUnauthRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: appauthRolesample1
        Path: /
        AssumeRolePolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Principal:
                Federated: "cognito-identity.amazonaws.com"
              Action:
                - "sts:AssumeRoleWithWebIdentity"
              Condition:
                StringEquals:
                  "cognito-identity.amazonaws.com:aud":
                    Ref: CognitoIdentityPool
                "ForAnyValue:StringLike":
                  "cognito-identity.amazonaws.com:amr": unauthenticated
        Policies:
          - PolicyName: "CognitoUnauthorizedPolicy"
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: "Allow"
                  Action:
                    - "mobileanalytics:PutEvents"
                    - "cognito-sync:*"
                    - "cognito-identity:*"
                  Resource: "*"
    CustomUserOnboardingRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: CustomUserRolecoginito1
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: CustomCloudWatchLogsPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - logs:CreateLogGroup
                    - logs:CreateLogStream
                    - logs:PutLogEvents
                  Resource:
                    - 'Fn::Join':
                      - ':'
                      -
                        - 'arn:aws:logs'
                        - Ref: 'AWS::Region'
                        - Ref: 'AWS::AccountId'
                        - 'log-group:/aws/lambda/*:*:*'
          - PolicyName: CustomUserOnboardingPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                  - dynamodb:Query
                  - dynamodb:DescribeTable
                  - dynamodb:Scan
                  - dynamodb:GetItem
                  - dynamodb:PutItem
                  - dynamodb:UpdateItem
                  - dynamodb:DeleteItem
                  Resource:
                    - 'Fn::Join':
                      - ':'
                      -
                        - 'arn:aws:dynamodb'
                        - Ref: 'AWS::Region'
                        - Ref: 'AWS::AccountId'                      
                        - 'table/${self:custom.settings.POSTS_TABLE}'
                - Effect: Allow
                  Action:
                  - cognito-idp:AdminAddUserToGroup
                  Resource:
                    Fn::Join:
                    - ''
                    - - 'arn:aws:cognito-idp:'
                      - Ref: AWS::Region
                      - ':'
                      - Ref: AWS::AccountId             


    PostsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDeFinitions:
        - AttributeName: Pk_id
          AttributeType: "S"  
        - AttributeName: Sk_id
          AttributeType: "S"  
        - AttributeName: cat_type
          AttributeType: "S"
    
        KeySchema:
        - AttributeName: "Pk_id"
          KeyType: "HASH"
        - AttributeName: "Sk_id"
          KeyType: "RANGE"
        TableName: ${self:custom.settings.POSTS_TABLE}
        GlobalSecondaryIndexes:
          - IndexName: empIdindex
            KeySchema:
              - AttributeName: cat_type
                KeyType: HASH
              - AttributeName: Sk_id
                KeyType: RANGE
            Projection:
              ProjectionType: 'ALL'
                 
        TimetoLiveSpecification:
          AttributeName: ttl
          Enabled: true
        BillingMode: PAY_PER_REQUEST

我在我的 handler.js 中编写了 2 个方法来创建用户池并将新用户分配给 AdminGroup。第一个函数工作正常,数据库更新了新条目。似乎没有调用第二个函数。 我的处理程序代码

'use strict';
const AWS = require('aws-sdk');
const db = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });
const { v4: uuidv4 } = require('uuid');
const deptTable = process.env.TABLE_NAME;
function response(statusCode,message,callback) {
        console.log(message);
  return {
    statusCode: statusCode,body: JSON.stringify(message)
  };

}

module.exports.createPost = (event,context,callback) => {
  //const reqBody = JSON.parse(event.body);
  var params = {
    TableName: deptTable,Item:{
      Pk_id: uuidv4(),Sk_id : uuidv4(),cat_type: "Administrator",emp_createdate: new Date().toISOString(),UserPoolId: event.userPoolId,Username: event.userName
    }
};
db.put(params,function(err,data) {
  if (err) {
      console.log("Error",err)
  } else {
      console.log("PutItem succeeded");    
     
  context.done(null,event);
  }
});


  
}
module.exports.adminAddUserToGroup = (event,callback)=> {
       console.log('before')
    var cognitoidentityserviceprovider = new aws.CognitoIdentityServiceProvider();

    var params = {
        GroupName: 'Administrator',Username: event.userName
    };

    console.log('before')
    cognitoidentityserviceprovider.adminAddUserToGroup(params)
    .promise()
    .then(() => callback(null,event))
    .catch(err => callback(err,event));  
    context.done(null,event);  
}



// Get employee Details by using Id
module.exports.getEmployeeDetails = (event,callback) => {
  const id = event.pathParameters.id;
  
  const params = {
    KeyConditionExpression: 'Sk_id = :Sk_id AND cat_type = :cat_type',ExpressionAttributeValues: {
      ":Sk_id": id,":cat_type": "Stud"
    },TableName: deptTable,IndexName:"empIdindex"   
};
db.query(params,(error,result) => {
  // handle potential errors
  if (error) {
    console.error(error);
    callback(null,{
      statusCode: error.statusCode || 501,headers: { 'Content-Type': 'text/plain' },body: JSON.stringify(error),});
    return;
  }

  // create a response
  const response = {
    statusCode: 200,body: JSON.stringify(result.Items),};
  callback(null,response);
});
}

我是 Aws 的新手,如果我错了,请纠正我

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。