如何使用Amplify-android AWS使用Lambda函数从Cognito查询用户池

问题描述

我在schema.graphql上具有此功能签名,我可以使用它来调用从Cognito服务器检索用户列表的lambda函数吗?

type Query 
{
  echo(msg: String): String @function(name: "getUsers-${env}")
}

如何从Android调用它?

我需要阿波罗吗?

扩增库够吗?

解决方法

基本上,您不能直接使用架构从Cognito Amazon服务器中挖掘用户。

在Android应用程序中,您必须创建并使用以下Amplify插件,您可以从此处了解更多信息: https://docs.amplify.aws/start/q/integration/android

您必须按照以下说明创建lambda函数:

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18',region: 'eu-central-1'});

exports.handler = async (event) => {
    // TODO implement
    let users = [];
    let roles = ['admin','user' ];

    try
    {
        // (let i=0,len=roles.length; i<len; i++) 
        //{
            //const role = roles[i];
            let more = true;
            let nextToken = '';
    
            while (more) 
            {
                let params = {
                  UserPoolId: "your pool id",//GroupName: role,Limit: 60
                };
                
                if (nextToken !== '')
                {
                    params.NextToken = nextToken;
                } 
                
                const rawUsers = await cognito.listUsers(params).promise();
                const mapUsers = rawUsers.Users.map(user => {
                
                    let atts = {};
        
                    for (const att of user.Attributes) 
                    {
                        atts[att.Name] = att.Value;
                    }
        
                    return {
                        username: user.Username,name: atts.hasOwnProperty('name') ? atts.name : '',email: atts.hasOwnProperty('email') ? atts.email : '',status: user.UserStatus,//role: role
                    };
              
                
                });
            
                users= users.concat(mapUsers);
                if (rawUsers.hasOwnProperty('NextToken')) {
                  nextToken = rawUsers.NextToken;
                } else {
                  more = false;
                }
                    }
            
            
       // }
        
        const response = {
            statusCode: 200,//  Uncomment below to enable CORS requests
        //  headers: {
        //      "Access-Control-Allow-Origin": "*"
        //  },body: JSON.stringify(users),};
        return response;
   
    }
    catch(e)
    {
        const response = {
            statusCode: 500,body: e,};
        return response;
    }
};

然后创建REST api: 使用终端Amplify CLI命令并将其连接到已创建的lambda函数,包括“仅限经过身份验证的用户”。 运行:

amplify add api
C:\DOV_AWS>amplify api add
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the
 project: users
? Provide a path (e.g.,/book/{isbn}):
C:\DOV_AWS>amplify api add
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the
 project: DOV
? Provide a path (e.g.,/book/{isbn}): /users
? Choose a Lambda source Use a Lambda function already added in the current Amplify projec
t
? Choose the Lambda function to invoke by this path getUsers
? Restrict API access Yes
? Who should have access? Authenticated users only
? What kind of access do you want for Authenticated users? create,read,update,delete
? Do you want to add another path? No
Successfully added resource DOV locally

使用amplify push命令: 放大推送

为了更新云上的API。

在您的应用中运行以下代码,以获取用户。


   RestOptions options = RestOptions.builder()
                        .addPath("/users")
                        .build();

                        Amplify.API.get("Users",options,response -> 
                        Log.i("MyAmplifyApp"," ! ! ! ! ! Data Respond ! ! ! ! !" 
                        + response.getData().asString()),error -> Log.e("MyAmplifyApp","GET failed",error)
   );

                                      

您必须在lambda函数中添加Cognito服务器的权限规则,才能获取用户数据。

身份验证方法将包括IAM规则