AWS Cognito / Amplify - 将新用户注册自动添加到用户组

时间:2018-04-23 14:51:15

标签: amazon-web-services aws-cognito aws-mobilehub aws-appsync aws-amplify

我正在使用AWS Amplify库为AppSync项目注册并执行Auth。这使用Cognito。但是,当新用户通过Amplify / Cognito注册时,新用户不会分配到cognito池中的任何特定组。我正在使用Amplify高阶组件进行登录/注册。

import { withAuthenticator } from 'aws-amplify-react';

我将一个组件

包裹起来
class Authenticator extends React.Component {
   //... basically empty component, only exists so I can wrap it w/ the HOC
}
export default withAuthenticator(Authenticator)

Amplify在index.js

中设置
import config from './aws-exports';
import Amplify from 'aws-amplify';
Amplify.configure(config);

aws-exports.js由AWS Mobile Hub CLI自动生成。看起来像......

const awsmobile = {
    'aws_app_analytics': 'enable',
    'aws_cognito_identity_pool_id': 'us-west-2:XXX',
    'aws_cognito_region': 'us-west-2',
    'aws_content_delivery': 'enable',
    'aws_content_delivery_bucket': 'flashcards-hosting-mobilehub-XXX',
    'aws_content_delivery_bucket_region': 'us-west-2',
    'aws_content_delivery_cloudfront': 'enable',
    'aws_content_delivery_cloudfront_domain': 'XXX.cloudfront.net',
    'aws_mandatory_sign_in': 'enable',
    'aws_mobile_analytics_app_id': 'XXX',
    'aws_mobile_analytics_app_region': 'us-east-1',
    'aws_project_id': 'XXX',
    'aws_project_name': 'flash-cards',
    'aws_project_region': 'us-west-2',
    'aws_resource_name_prefix': 'flashcards-mobilehub-XXX',
    'aws_sign_in_enabled': 'enable',
    'aws_user_pools': 'enable',
    'aws_user_pools_id': 'us-west-2_XXX',
    'aws_user_pools_mfa_type': 'OFF',
    'aws_user_pools_web_client_id': 'XXX',
}
export default awsmobile;

4 个答案:

答案 0 :(得分:11)

我得到了它的工作。正如Vladamir在评论中所提到的,这需要在服务器端完成,在Post Confirmation lambda触发器中。这是lambda函数。

'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
  });  
};

您还必须为lambda函数角色设置策略。在IAM控制台中,找到此lambda的角色并添加此内联策略。这使得lambda成为了城堡的钥匙,因为它可以让你更具限制性。

{
    "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": "*"
        }
    ]
}

答案 1 :(得分:6)

Cognito不会知道新注册用户需要加入哪个组。您必须以编程方式(或手动)将用户分配给特定组。一旦您的代码将用户置于特定组中,JWT ID令牌将包含此用户所属的所有相关组/ IAM角色的列表。

有关群组here的更多信息。

答案 2 :(得分:1)

AWS Amplify增加了对使用Amplify cli将用户添加到组中的支持。详细信息在这里 https://aws.amazon.com/blogs/mobile/amplify-framework-adds-supports-for-aws-lambda-triggers-in-auth-and-storage-categories/

本文还介绍了更多详细信息 https://medium.com/@dantasfiles/multi-tenant-aws-amplify-method-2-cognito-groups-38b40ace2e9e

将组名从客户端传递给您的lamda函数,您可以使用后确认Lambda触发参数clientMetadata对象,如下所示。

  await Auth.signUp({
          username: this.email,
          password: this.password,
          attributes: {
            given_name: this.firstname,
            family_name: this.lastname
          },
          clientMetadata: {
            key: value
          }
        })

如果您使用现成的放大身份验证UI,则需要自定义withAuthenticator组件并编写自己的组件以进行注册或首选的ConfirmSignUp(请检查是否可以从此处传递clientMetadata)

在lamda函数中,您可以像这样传递组名

event.request.clientMetadata.groupName

答案 3 :(得分:0)

您必须首先使用运行amplify update auth的amplify cli添加管理员查询,之后您必须仅阻止管理员用户的管理员查询,您将在amplify/backend/function/中看到输出代码

在您进行更改后,您可以使用:

async function addToGroup() { 
    let apiName = 'AdminQueries';
    let path = '/addUserToGroup';
    let myInit = {
        body: {
          "username" : "username",
          "groupname": "groupname"
        }, 
        headers: {
          'Content-Type' : 'application/json',
          Authorization: `${(await Auth.currentSession()).getAccessToken().getJwtToken()}`
        } 
    }
    return await API.post(apiName, path, myInit);
}

为了使用放大将用户添加到角色中,如果仅通过电子邮件注册,请检查用户ID。 https://aws.amazon.com/es/blogs/mobile/amplify-framework-adds-supports-for-aws-lambda-triggers-in-auth-and-storage-categories/

上有此放大变化的文档。