简体   繁体   中英

How to add a user into a AWS Cognito userpool group?

I'm using AWS Cognito to implement the user sign-up and sign-in in my iOS APP (Swift).

When a user signed up, I want to add the user into a specified user pool group which has already been created in my cognito user pool.

I have tried the swift code bellow, but it doesn't seem to work.

After the user signing up, he or she push the [addToGroup] button to join the user pool group named [GroupA].

@IBAction func addToGroupButton(_ sender: Any) {
        let request = AWSCognitoIdentityProviderAdminAddUserToGroupRequest()
        request?.groupName = "GroupA"
        request?.userPoolId = "ap-northeast-1_8H0k*****"
        request?.username = eMailAdd

        let identityProvider = AWSCognitoIdentityProvider()
        identityProvider.adminAddUser(toGroup: request!).continueWith { (task) -> Any? in
            DispatchQueue.main.async(execute: {
                if let error = task.error {
                    print("\(error.localizedDescription)")
                }
            })
        }
    }

There is no problem for the user to sign-up, and I can confirm the information the user signed up. BUT, the user name just doesn't appear in the GroupA.

Could anybody tell me what's wrong with my code?? THANK YOU!!

I assume you get some error like AWSCognitoIdentityProviderErrorNotAuthorized. As this is a 'admin' API call which 'Requires developer credentials' as suggested here [0].

I would suggest you to hardcode your credential to test if this API call works first

AWSStaticCredentialsProvider *credentialsProvider = [AWSStaticCredentialsProvider credentialsWithAccessKey:"your-access-key" secretKey:"your-secret-key"];
AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
[AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;

Please note do not hardcode your credential in your production environment.

21/07/2019 update:

let staticCredentialProvider = AWSStaticCredentialsProvider.init(accessKey: "yourAccessKey", secretKey: "yourSecretKey")
let configuration = AWSServiceConfiguration.init(region: .APSoutheast2, credentialsProvider: staticCredentialProvider)
AWSServiceManager.default()?.defaultServiceConfiguration = configuration

let request = AWSCognitoIdentityProviderAdminAddUserToGroupRequest()
request?.groupName = "GroupA"
request?.userPoolId = "ap-southeast-2_xxxxxxxxx"
request?.username = "yourUserName"


    AWSCognitoIdentityProvider.default().adminAddUser(toGroup: request!).continueWith { (task) -> Any? in
        DispatchQueue.main.async(execute: {
            if let error = task.error {
                print("\(error.localizedDescription)")
            }
        })
    }

I have tested, the above code is working in my test environment. I list it here for your reference. The next step will be trying to remove hardcoded credential from the codebase. Instead of using AWSStaticCredentialsProvider, temp credentials can be acquired using Cognito identity pool. I reckon with adequate permission, this flow can work without developer credential.

26/07/2019 update:

// using Cognito userpool with identity pool, to provider credential to AWSServiceManager
let serviceConfiguration = AWSServiceConfiguration(region: .APSoutheast2, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YourUserPoolClientId", clientSecret: "YourUserPoolClientSecret", poolId: "YourUserPoolId")
AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "RandomStringForIdentifyingYourPoolWithinThisApp")
let pool = AWSCognitoIdentityUserPool(forKey: "RandomStringForIdentifyingYourPoolWithinThisApp")
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APSoutheast2, identityPoolId: "YourIdentityPoolId", identityProviderManager:pool)

let configuration = AWSServiceConfiguration.init(region: .APSoutheast2, credentialsProvider: credentialsProvider)
AWSServiceManager.default()?.defaultServiceConfiguration = configuration

// sign in a user
pool.getUser("UserNameOfAUserInYourPool").getSession("UserNameOfAUserInYourPool", password: "PasswordOfAUserInYourPool", validationData: nil).continueWith { (task) -> Any? in
    if let error = task.error {
        print("user sign in error: \(error.localizedDescription)")
    } else {
        print("user session is: \(String(describing: task.result))")
    }

    // add a user to GroupA
    let request = AWSCognitoIdentityProviderAdminAddUserToGroupRequest()
    request?.groupName = "GroupA"
    request?.userPoolId = "YourUserPoolId"
    request?.username = "UserNameOfAUserInYourPool"

    return AWSCognitoIdentityProvider.default().adminAddUser(toGroup: request!)
    }.continueWith { (task) -> Any? in
        if let error = task.error {
            print("cannot add user to group \(error.localizedDescription)")
        }
}

Like I suggested, this is the solution without hardcoded AWS credential. Cognito Identity pool provides temperature AWS credential after user sign in to Cognito user pool [3], which enables the 'adminAddToGroup' API call.

Along with the above code, you also need to setup your Cognito identity pool on AWS console, or using AWS CLI. You can find the details in the screenshot.

configuring_identity_pool

You also need to create an auth IAM role for authenticated user to assume. Here is the policy example.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "cognito-idp:AdminRemoveUserFromGroup",
                "cognito-idp:AdminAddUserToGroup"
            ],
            "Resource": "Your_userpool_ARN"
        }
    ]
}

Reference: [0] https://aws-amplify.github.io/aws-sdk-ios/docs/reference/Classes/AWSCognitoIdentityProvider.html#//api/name/adminAddUserToGroup : [2] https://aws.amazon.com/blogs/mobile/how-amazon-cognito-keeps-mobile-app-users-data-safe/ [3] https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-integrating-user-pools-with-identity-pools.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM