简体   繁体   English

该身份池和用户池不支持未经身份验证的访问

[英]Unauthenticated access is not supported for this identity pool with user pool

I have a Cognito User Pool to sign up/in my users from an app and then use Cognito Identity to provide authentication. 我有一个Cognito用户池,可以通过一个应用程序注册/登录我的用户,然后使用Cognito身份提供身份验证。 I have disabled unauthenticated users. 我已禁用未经身份验证的用户。 Once the user sign up, the user is created in the Pool. 用户注册后,将在池中创建该用户。 When he signs in, the identity is created in the Identity pool and I can see that this identity is linked to the user pool (linked login). 当他登录时,将在身份池中创建该身份,并且我可以看到该身份已链接到用户池(链接登录)。 However, when the user tried to get access to AWS resources (Dynamo, Lambda function, etc.) the call returns "Unauthenticated access is not supported for this identity pool" . 但是,当用户尝试访问AWS资源(Dynamo,Lambda函数等)时,调用将返回“此身份池不支持未经身份验证的访问” I am however able to get the user details and the identity id which is the one created in the identity pool. 但是,我可以获取用户详细信息和标识ID,这是在标识池中创建的标识。

This is the code I use: 这是我使用的代码:

func cognitoUserPoolInit(window:UIWindow, debugLogFiles: DebugLogFiles) {
    self.window = window

    //Configure Cognito Identity User Pool. Edit ConstantAWS to change pool
    let serviceConfiguration = AWSServiceConfiguration(region: K.COGNITO_REGIONTYPE, credentialsProvider: nil)
    let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: K.COGNITO_USER_POOL_APP_CLIENT_ID, clientSecret: K.COGNITO_USER_POOL_APP_CLIENT_SECRET, poolId: K.COGNITO_USER_POOL_ID)

    AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithConfiguration(serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "UserPool")

    self.pool = AWSCognitoIdentityUserPool(forKey: "UserPool")
    self.pool!.delegate = self
    self.cognitoIdentityUser = self.pool!.currentUser()
}

func getCognitoUserPoolUserId() {
            self.cognitoIdentityUser!.getDetails().continueWithBlock() { (task) in
                dispatch_async(dispatch_get_main_queue()) {
                    self.needtoGetCognitoUserId = false
                    if task.error != nil {  // some sort of error
                        let alert = UIAlertController(title: "", message: task.error?.userInfo["message"] as? String, preferredStyle: UIAlertControllerStyle.Alert)
                        alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))

                        NSLog("Domain: " + (task.error?.domain)! + " Code: \(task.error?.code)")

                        if task.error?.code == NSURLErrorNotConnectedToInternet {
                            self.lastError = (task.error?.code)!
                            //no internet connection. Fire a timer to get our credential as soon as network is back
                            let internetOfflineTimer:NSTimer =  NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(UserPool.internetOffline), userInfo: nil, repeats: false)
                            dispatch_async(dispatch_get_main_queue(), {() -> Void in
                                NSRunLoop.mainRunLoop().addTimer(internetOfflineTimer, forMode: NSDefaultRunLoopMode)
                            })
                        } else {
                            if task.error?.userInfo["message"] != nil {
                                NSLog(task.error?.userInfo["message"] as! String)

                            }
                        }
                    } else {
                        // I got no error
                        // i got the username earlier - use it
                        self.lastError = 0
                        if let response: AWSCognitoIdentityUserGetDetailsResponse = task.result as? AWSCognitoIdentityUserGetDetailsResponse {
                            var sub: String?
                            for attribute in response.userAttributes! {
                                if attribute.name == "sub" {
                                    sub = attribute.value
                                    NSLog("sub:" + sub!)
                                    break;
                                }

                            }
                            //if the user Id, then go ahead and get the dynamoDB table
                            if sub != nil {
                                self.cognitoUserPoolUserId = sub
                                self.getCognitoIdentity()
                            } else {
                                NSLog("UserId not found in response")
                            }
                        }
                    }
                }


                return nil
            }

      }


    func getCognitoIdentity() -> Bool {
    // Initialize the Amazon Cognito credentials provider

    //get pool id from plist (Federated Identieis pool not User pool)
    var myDict: NSDictionary?
    var identityPoolID: String?
    var region: String?
    //PoolId points to TestIDPool in the Federated Identitied/West region for test purpose
    if let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist") {
        myDict = NSDictionary(contentsOfFile: path)
        identityPoolID = myDict!.objectForKey("AWS")!.objectForKey("CredentialsProvider")!.objectForKey("CognitoIdentity")!.objectForKey("Default")!.objectForKey("PoolId")! as? String;
        region = myDict!.objectForKey("AWS")!.objectForKey("CredentialsProvider")!.objectForKey("CognitoIdentity")!.objectForKey("Default")!.objectForKey("Region") as? String;
    } else {
        return false
    }

    self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: region!.aws_regionTypeValue(), identityPoolId: identityPoolID!, identityProviderManager:self.pool)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: self.credentialsProvider)

    transferManager = AWSS3TransferManager.defaultS3TransferManager()


    // Retrieve your Amazon Cognito ID
    self.credentialsProvider!.getIdentityId().continueWithBlock { (task: AWSTask!) -> AnyObject! in
        if (task.error != nil) {
            print("Error: " + task.error!.localizedDescription)
        }
        else {
            // the task result will contain the identity id
            print("cognitoId: " + self.credentialsProvider!.identityId!)
            //At this point we get the identity to query the database
            self.queryLatestItem()
        }
        return nil
    }
    return true
}


func queryLatestItem() {
        let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

        let queryExpression = AWSDynamoDBQueryExpression()
    queryExpression.scanIndexForward = false
    queryExpression.limit = 1
    queryExpression.keyConditionExpression = "userId = :UID"
    queryExpression.expressionAttributeValues = [":UID" : (self.cognitoUserPoolUserId)!]

    dynamoDBObjectMapper .query(StatisticsDB.self, expression: queryExpression) .continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
        if (task.error != nil) {
            print("Error: \(task.error)") --> this is where i get the unauthenticated error.....
...

cognitoUserPoolInit() is called from the appDelegate and getCognitoUserPoolUserId() when the user get to the UI requiring DynamoDB data. cognitoUserPoolInit()从的appDelegate和称为getCognitoUserPoolUserId()当用户到达需要DynamoDB数据的UI。

If I select "Enable access to unauthenticated identities" in the federated pool, it works fine. 如果我在联合池中选择“启用对未经身份验证的身份的访问”,则可以正常工作。

Also, I have a web app and can sign in, authenticated correctly and get access to AWS services without any problem. 另外,我有一个Web应用程序,可以登录,正确进行身份验证并可以毫无问题地访问AWS服务。 So too me, my AWS/roles configuration should be good and probably something wrong is happening on the app side. 我也是,我的AWS /角色配置应该很好,并且应用程序端可能发生了问题。

I do not understand how I could get the user details and correct identity id (from print("cognitoId: " + self.credentialsProvider!.identityId!) ) and get an unauthenticated error. 我不明白如何获取用户详细信息和正确的身份ID(从print("cognitoId: " + self.credentialsProvider!.identityId!) )并获得未经身份验证的错误。

Restarting again the app gives slightly different error: 再次重新启动该应用程序会给出稍微不同的错误:

{
    Connection = "keep-alive";
    "Content-Length" = 129;
    "Content-Type" = "application/x-amz-json-1.1";
    Date = "Sun, 29 Jan 2017 20:04:06 GMT";
    "x-amzn-ErrorMessage" = "Access to Identity 'us-west-2:714eccXXXa5-42d8-8b29-5e2XXXXXXX' is forbidden.";
    "x-amzn-ErrorType" = "NotAuthorizedException:";
    "x-amzn-RequestId" = "16fc81c2-e65e-11e6-9643-756bf858abb7";
}

Added role permissions for auth I use: 为我使用的身份验证添加了角色权限:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*",
                "dynamodb:*",
                "lambda:*",
                "s3:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

and the trust relationship 和信任关系

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "us-west-2:7cXXXX5f-b91e-4fc9-a72c-6f91XXXXXXX"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "authenticated"
        }
      }
    }
  ]
}

I was able to find the root cause. 我找到了根本原因。 The following line will re-init the service configuration previously set: 以下行将重新初始化先前设置的服务配置:

let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

So I replaced this previous line with: 因此,我用以下内容替换了前一行:

let objectMapperConfiguration = AWSDynamoDBObjectMapperConfiguration()        
serviceConfig = AWSServiceConfiguration(region: .USWest2, credentialsProvider: self.credentialsProvider)
AWSDynamoDBObjectMapper.registerDynamoDBObjectMapperWithConfiguration(serviceConfig!, objectMapperConfiguration: objectMapperConfiguration, forKey: "USWest2DynamoDBObjectMapper")

let dynamoDBObjectMapper = AWSDynamoDBObjectMapper(forKey: "USWest2DynamoDBObjectMapper")

See "Configure AWS Credentials in Your Files Using Amazon Cognito" http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Js.Summary.html In that example, they create an unauthenticated role for that type of access. 请参阅“使用Amazon Cognito配置文件中的AWS凭证” http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Js.Summary.html在该示例中,它们为该类型的未授权身份创建未经身份验证的角色访问。 Hopefully that helps you. 希望对您有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS Cognito:“此身份池不支持未经身份验证的访问权限。” - AWS Cognito: “Unauthenticated access is not supported for this identity pool.” AWS / iOS / Cognito:此身份池不支持未经身份验证的访问 - AWS / iOS / Cognito: unauthenticated access is not supported for this identity pool iOS-使用Facebook登录,但仍然得到:“此身份池不支持未经身份验证的访问” - iOS - Login in with Facebook but still getting: “Unauthenticated access is not supported for this identity pool” 使用DynamoDB时,此标识池不支持未经身份验证的访问 - Unauthenticated access is not supported for this identity pool, while using DynamoDB 将DynamoDB与Cognito一起使用:令牌不是来自此身份池的受支持提供商 - Using DynamoDB With Cognito: Token is not from a supported provider of this identity pool 如何使用Cognito Identity以信任关系指定Amazon AWS User Pool - How to specify Amazon AWS User Pool in trust relationship with Cognito Identity 亚马逊认知和身份池问题 - Amazon cognito and Identity pool issue 卓(AWS):如何根据Cognito池正确认证用户并将其用于Cognito联合身份? - AWS: How to properly authenticate a user against Cognito Pool and use it for Cognito Federated Identity? AWS Cognito联合身份池-身份验证角色 - AWS Cognito Federated Identity Pool - Role on Authentication 无法找到Amazon Cognito Identity Pool - Amazon Cognito Identity Pool can not be found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM