AWS Cognito/Amplify - have new user sign ups be automatically add to a user group

前端 未结 4 2138
悲哀的现实
悲哀的现实 2020-12-24 09:24

I am using AWS Amplify library to sign up and perform Auth for an AppSync project. This uses Cognito. However, when a new user signs up via Amplify/Cognito, the new user

4条回答
  •  长情又很酷
    2020-12-24 10:03

    I got it working. As mentioned by Vladamir in the comments this needs to be done server side, in a Post Confirmation lambda trigger. Here is the lambda function.

    'use strict';
    var AWS = require('aws-sdk');
    module.exports.addUserToGroup = (event, context, callback) => {
      // console.log("howdy!",event);
      var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
      var params = {
        GroupName: 'users', //The name of the group in you cognito user pool that you want to add the user to
        UserPoolId: event.userPoolId, 
        Username: event.userName 
      };
      //some minimal checks to make sure the user was properly confirmed
      if(! (event.request.userAttributes["cognito:user_status"]==="CONFIRMED" && event.request.userAttributes.email_verified==="true") )
        callback("User was not properly confirmed and/or email not verified")
      cognitoidentityserviceprovider.adminAddUserToGroup(params, function(err, data) {
        if (err) {
          callback(err) // an error occurred
        }
        callback(null, event);           // successful response
      });  
    };
    

    You will also have to set the policy for the lambda function role. In the IAM console, find the role for this lambda and added this inline policy. This give the lambda the keys to the castle for everything cognito so make yours more restrictive.

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "cognito-identity:*"
                ],
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "cognito-sync:*"
                ],
                "Resource": "*"
            },
            { //this might be the only one you really need
                "Effect": "Allow",
                "Action": [
                    "cognito-idp:*"
                ],
                "Resource": "*"
            }
        ]
    }
    

提交回复
热议问题