无法假定使用Developer Authentication Swift Cognito进行身份验证

时间:2015-12-07 23:21:35

标签: ios swift amazon-web-services aws-sdk amazon-cognito

我可以从LambdAuth(我的开发人员身份验证)成功检索令牌和身份,但是当我尝试使用服务时,Cognito会假定一个未经身份验证的角色。这是我的错误:

Error Domain=com.amazonaws.AWSDynamoDBErrorDomain Code=1 "(null)" UserInfo={Message=User: arn:aws:sts::xxxxxxxxxx:assumed-role/Cognito_LambdAuthUnauth_Role/CognitoIdentityCredentials is not authorized to perform: dynamodb:ListTables on resource: *, __type=com.amazon.coral.service#AccessDeniedException}

我期待这个角色是CognitoLambdAuthAuth_Role。

这是我的身份提供者代码:

//  MyIdentityProvider.swift

import Foundation
import AWSCore
import AWSCognito
import AWSLambda

class MyIdentityProvider: AWSAbstractCognitoIdentityProvider {
    var _token: String!
    var _logins: [ NSObject : AnyObject ]!

    var email: String!
    var password: String!

    override var token: String {
        get {
            return _token
        }
    }

    override var logins: [ NSObject : AnyObject ]! {
        get {
            return _logins
        }
        set {
            _logins = newValue
        }
    }

    override func getIdentityId() -> AWSTask! {

        if self.identityId != nil {
            return AWSTask(result: self.identityId)
        }else{
            return AWSTask(result: nil).continueWithBlock({ (task) -> AnyObject! in
                if self.identityId == nil {
                    return self.refresh()
                }
                return AWSTask(result: self.identityId)
            })
        }
    }

    override func refresh() -> AWSTask! {

        let invocationRequest = AWSLambdaInvokerInvocationRequest()
        invocationRequest.functionName = "LambdAuthLogin"
        invocationRequest.invocationType = AWSLambdaInvocationType.RequestResponse
        invocationRequest.payload = ["email" : "me@example.com", "password" : "password"]

        //self.activeSearchRequest = invocationRequest

        let lambdaInvoker = AWSLambdaInvoker.defaultLambdaInvoker()
        let task = lambdaInvoker.invoke(invocationRequest).continueWithSuccessBlock() { (task) -> AWSTask! in
            if (task.error != nil) {
                // failed to retrieve token.
                print("Error invoking lambda function: ", task.error)
            } else {
                //print("response: ", task.result)
                if let payload = task.result.payload as? [String: AnyObject] {
                    if(payload["login"] as! Int == 1) {
                        // The following 3 lines are required as referenced here: http://stackoverflow.com/a/26741208/535363
                        var tmp = NSMutableDictionary()
                        tmp.setObject(self.email, forKey: "cognito-identity.amazonaws.com")
                        self.logins = tmp as [NSObject : AnyObject]

                        self.identityId = payload["identityId"] as! String
                        self._token = payload["token"] as! String

                    }
                    print("id", payload["identityId"])
                    print("token: ", payload["token"])
                    print("logins map", self.logins)
                }
            }
            return task
        }
        return task            
    }
}

这是我调用生成错误的DynamoDB调用的地方:

let dynamoDB = AWSDynamoDB.defaultDynamoDB()
let listTableInput = AWSDynamoDBListTablesInput()
print("listing dynamoDB tables..")
let finalTask = dynamoDB.listTables(listTableInput).continueWithBlock{ (task: AWSTask!) -> AnyObject! in
    if (task.error != nil) {
        // failed to retrieve identityId.
        if let handler = completionHandler {
            print("Store Data Error occurred: \(task.error)")
            handler(false)
        }
        return task
    } else {
        print("Store Data Succeeded...")
        let listTablesOutput = task.result as! AWSDynamoDBListTablesOutput

        for tableName : AnyObject in listTablesOutput.tableNames {
            print("\(tableName)")
        }
        if let handler = completionHandler {
            handler(true)
        }
        return task
    }
}

在DynamoDB调用之前检索身份的代码:

    func getAuthCognitoId(email: String, password: String, identityProvider: MyIdentityProvider)->AWSTask! {
        identityProvider.email = email
        identityProvider.password = password
        // TODO: Store to a keychain

        let task = identityProvider.getIdentityId().continueWithSuccessBlock() { (task) -> AWSTask! in

            let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityProvider: identityProvider, unauthRoleArn: Constants.ARNUnauth.value, authRoleArn: Constants.ARNAuth.value)
            let defaultServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)
            AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration
            return task
        }
        return task
    }

编辑12/8/15:

我在lambda函数前面添加了API Gateway,但仍无法获得授权角色。然而,它成功地检索了令牌和idenityId:

override func refresh() -> AWSTask! {

    let task = AWSTaskCompletionSource()
    let request = AFHTTPRequestOperationManager()
    request.requestSerializer.setValue(email, forHTTPHeaderField: "email")
    request.requestSerializer.setValue(password, forHTTPHeaderField: "password")
    request.GET(Constants.loginUrl.value, parameters: nil, success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
        print("request: ", request)
        // The following 3 lines are required as referenced here: http://stackoverflow.com/a/26741208/535363
        self.logins = [self.developerProvider: self.email]

        // Get the properties from my server response
        print("response: ", response)
        let identityId = response.objectForKey("identityId")as! String
        let token = response.objectForKey("token")as! String

        // Set the identityId and token for the ExampleAppIdentityProvider
        self.identityId = identityId
        self._token = token

        task.setResult(self.identityId)
        }, failure: { (request: AFHTTPRequestOperation?, error: NSError!) -> Void in
            task.setError(error)
    })
    return task.task
}

1 个答案:

答案 0 :(得分:2)

问题是您使用unauth凭证调用lambda

{{1}}

由于它将这些凭据存储在后续请求的密钥链中,并且仅在它们到期时刷新它们,因此在调用DDB时仍然使用unauth凭据。尝试使用api-gateway向你的lambda auth面对面,这样你就不需要像你的评论所提到的那样开始,如果你还有问题,请告诉我。