如何通过经过身份验证的 cognito 用户(用户池)快速访问 DynamoDB

Posted

技术标签:

【中文标题】如何通过经过身份验证的 cognito 用户(用户池)快速访问 DynamoDB【英文标题】:How to access DynamoDB by authenticated cognito user (user pool) in swift 【发布时间】:2016-10-25 10:59:41 【问题描述】:

我正在尝试将 AWS Cognito(用户池)和 AWS DynamoDB 用于我的移动应用程序。

我做了以下事情:

    在 AWS Cognito 上创建用户池。 在 AWS Cognito 上创建身份池并将用户池 ID、应用程序客户端 ID 设置为身份验证提供程序上的 Cognito。 在 AWS DynamoDB 上创建 SampleTable。 设置权限验证角色以访问 AWS IAM 上的 SampleTable。

我创建了这段代码:

let userPoolConfigration = AWSServiceConfiguration.init(region: AWSRegionType.USEast1, credentialsProvider: nil)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = userPoolConfigration

let userServiceConfigration = AWSCognitoIdentityUserPoolConfiguration.init(clientId: "(client id from user pool)", clientSecret: "(client secret from user pool)", poolId: "(user pool id from user pool)")

AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithUserPoolConfiguration(userServiceConfigration, forKey: "AmazonCognitoIdentityProvider")
let pool = AWSCognitoIdentityUserPool(forKey: "AmazonCognitoIdentityProvider")

    let user = pool.getUser("sampleuser")
    user.getSession("sampleuser", password: "samplepassword", validationData: nil, scopes: nil).continueWithBlock( task in
        if (task.error == nil) 
            let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1,
                identityPoolId:"(identity id from identity pool)")

            let ret = task.result as! AWSCognitoIdentityUserSession
            let logins: NSDictionary = NSDictionary(dictionary: ["cognito-idp.us-east-1.amazonaws.com/(user pool id from user pool)" : ret.idToken!.tokenString])
            credentialsProvider.logins = logins as [NSObject : AnyObject]
            let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)
            AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
            credentialsProvider.clearKeychain()
            credentialsProvider.credentials().continueWithBlock (task: AWSTask!) -> AnyObject! in
                let result = task.result as! AWSCredentials
                let newcredentialsProvider = AWSStaticCredentialsProvider(accessKey:result.accessKey, secretKey: result.secretKey)
                let newdefaultServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: newcredentialsProvider)
                AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = newdefaultServiceConfiguration

                let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
                let scanExpression = AWSDynamoDBScanExpression()

                dynamoDBObjectMapper.scan(SampleTable.self, expression: scanExpression).continueWithBlock( task in
                    print(task.result)
                    return nil
                )
                return nil
            
        
        return nil
    )

但运行“dynamoDBObjectMapper.scan()”时出现此错误:

2016-06-23 16:57:04.988 AWSiosSDK v2.4.3 [Debug] AWSURLSessionManager.m line:525 | -[AWSURLSessionManager printHTTPHeadersAndBodyForRequest:] | Request headers:

    "Content-Type" = "application/x-amz-json-1.0";
    Host = "dynamodb.us-east-1.amazonaws.com";
    "User-Agent" = "aws-sdk-iOS/2.4.3 iPhone-OS/9.2 en_US mapper";
    "X-Amz-Date" = 20160623T075704Z;
    "X-Amz-Target" = "DynamoDB_20120810.Scan";

2016-06-23 16:57:04.988 if-she[3704:367618] AWSiOSSDK v2.4.3 [Debug] AWSURLSessionManager.m line:542 | -[AWSURLSessionManager printHTTPHeadersAndBodyForRequest:] | Request body:
"TableName":"SampleTable"
2016-06-23 16:57:05.844 AWSiOSSDK v2.4.3 [Debug] AWSURLSessionManager.m line:552 | -[AWSURLSessionManager printHTTPHeadersForResponse:] | Response headers:

    Connection = "keep-alive";
    "Content-Length" = 125;
    "Content-Type" = "application/x-amz-json-1.0";
    Date = "Thu, 23 Jun 2016 07:57:05 GMT";
    Server = Server;
    "x-amz-crc32" = 2088342776;
    "x-amzn-RequestId" = FPM78JRBQIKG2DOLI62SL4IRMFVV4KQNSO5AEMVJF66Q9ASUAAJG;

2016-06-23 16:57:05.845 AWSiOSSDK v2.4.3 [Debug] AWSURLResponseSerialization.m line:63 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body:
"__type":"com.amazon.coral.service#MissingAuthenticationTokenException","message":"Request is missing Authentication Token"

也许我错过了如何使用身份验证令牌。 我的代码有什么问题?

谢谢。

【问题讨论】:

【参考方案1】:

您可以尝试将会话令牌添加到newcredentialsProvider 吗?您将在结果中看到它以及访问密钥和密钥。

此外,一旦您将 Cognito 凭据提供程序添加为 defaultServiceConfiguration,您就无需显式获取凭据。您可以直接创建dynamoDBObjectMapper 实例,SDK 会在调用 Dynamo 或任何其他 AWS 服务时自动从 Cognito 拉取临时凭证。

【讨论】:

感谢您的回复。 AWSStaticCredentialsProvider 的初始化方法没有参数 sessionKey。所以我删除了代码“initialize AWSStaticCredentialsProvider”和“regist defaultServiceConfiguration it”但是我得到了同样的错误。

以上是关于如何通过经过身份验证的 cognito 用户(用户池)快速访问 DynamoDB的主要内容,如果未能解决你的问题,请参考以下文章

如何使用带有 iOS SDK 的 Facebook 身份验证通过 DynamoDB 和 Cognito 存储用户信息

AWS - JavaScript - 具有经过身份验证的 Cognito 用户对 DynamoDB 的 CRUD 操作

如何使用Facebook验证使用Cognito的API调用?

将 s3 文件下载限制为 cognito(首选)中经过身份验证的用户或任何人。他们应该只能查看但不能下载

如何在 API 网关中通过混合 Cognito 身份和用户池来授权 API

已通过身份验证的 Cognito 用户访问 DynamoDB 表的 AWS IAM 策略问题