用户显示在Auth0上但不在AWS Cognito Identity Pool中

时间:2016-11-24 07:55:45

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

好的,我正在构建一个iOS应用程序,它使用Auth0作为身份验证管理器和AWS来托管我的所有应用程序的其他功能。

但是,我可以使用Auth0创建和验证用户,但我无法让用户在我的AWS身份池中注册。

以下是我的代码:

// MARK: - IBAction Login
// This button brings up the Auth0 View Controller.
@IBAction func tryLogIn(_ sender: Any) {
    let controller = A0Lock.shared().newLockViewController()
    controller?.closable = true
    controller?.onAuthenticationBlock = { maybeProfile, maybeToken in
        // Do something to with token profile. e.g: save time. e.g:                save them.
        // Lock will not save the for you.

        // Now it is set up to save the information.
        guard
            let token = maybeToken,
            let refreshToken = token.refreshToken
            else {
                return
        }
        let keychain = A0SimpleKeychain(service: "Auth0")
        keychain.setString(token.idToken, forKey: "id_token")
        keychain.setString(refreshToken, forKey: "refresh_token")

            // The idToken does't exist, therefore the user has to enter their credentials to gain access.
            // Present the A0Lock login View Controller here.
            A0Lock.shared().present(controller, from: self)
            return
    }
    // MARK: - idToken exists
    // An idToken exists.
    // It needs to pass the validation test before access is granted.
    let keychain = A0SimpleKeychain(service: "Auth0")
    guard let idToken = keychain.string(forKey: "id_token") else {
        // Present the A0Lock login view controller here.
        A0Lock.shared().present(controller, from: self)
        return
    }

    // MARK: - idToken validation test.
    // To be useful the idToken has to pass the validation test! 
    // Initialize the validation test!
    let client = A0Lock.shared().apiClient()
    client.fetchUserProfile(withIdToken: idToken,
                            success: { profile in
    // The idToken is valid so it is safe to continue.
    // The fetched user profile is stored.
    keychain.setData(NSKeyedArchiver.archivedData(withRootObject: profile), forKey: "profile")
    // At this point, the user can log into the app by seguing to the next user interface.
    A0Lock.shared().present(controller, from: self)
    self.performSegue(withIdentifier: "CurrentlyLoggedIn", sender: nil)
    },
    failure: { error in
    // The idToken has expired or is no longer valid anymore.
    let keychain = A0SimpleKeychain(service: "Auth0")
    guard keychain.string(forKey: "refresh_token") != nil
        else
    {
        keychain.clearAll()
        return
    }
        let client = A0Lock.shared().apiClient()
        client.fetchNewIdToken(withRefreshToken: "refresh_token", parameters: nil, success: { (newToken) in
            // Congratulations, the user has now a new idToken!
            keychain.setString(newToken.idToken, forKey: "id_token")
            },
            failure: { (error) in
                // refreshToken is no longer required.
                // Cleaning stored values since they are no longer required.
                keychain.clearAll()
        })
    })

    // MARK: - Amazon AWS Cognito.
    // This should link the authentication methods together.
    // Initialize the Amazon Cognito credentials provider

    let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.apNortheast1,
                                                            identityPoolId:"ap-northeast-1:697ca223-9b17-4701-bb37-6ef201abde74")

    let configuration = AWSServiceConfiguration(region:.apNortheast1, credentialsProvider:credentialsProvider)

   AWSServiceManager.default().defaultServiceConfiguration = configuration


    // Declaring developer identity here.
    credentialsProvider.logins?["marcardian.au.auth0.com"]

    // Initialize the Cognito Sync client
    let syncClient = AWSCognito.default()

    // Create a record in a dataset and synchronize with the server
    let dataset = syncClient?.openOrCreateDataset("myDataset")
    dataset?.setString("myValue", forKey:"myKey")
    dataset?.synchronize().continue ({ (task: AWSTask!) -> AnyObject! in
        // Your handler code here
        return nil

    })
}

运行时它看起来像这样:

2016-11-24 18:33:18.654 FireStick[37559:520593] AWSiOSSDK v2.4.11 [Debug] AWSURLSessionManager.m line:553 | -[AWSURLSessionManager printHTTPHeadersForResponse:] | Responseheaders:
{
Connection = "keep-alive";
"Content-Length" = 111;
"Content-Type" = "application/x-amz-json-1.1";
Date = "Thu, 24 Nov 2016 07:33:17 GMT";
"x-amzn-ErrorMessage" = "Unauthenticated access is not supported for this identity pool.";
"x-amzn-ErrorType" = "NotAuthorizedException:";
"x-amzn-RequestId" = "44d2980b-b218-11e6-ae61-839aac944b5a";
}
2016-11-24 18:33:18.654 FireStick[37559:520593] AWSiOSSDK v2.4.11 [Debug] AWSURLResponseSerialization.m line:63 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body:
   {"__type":"NotAuthorizedException","message":"Unauthenticated access is not supported for this identity pool."}

1 个答案:

答案 0 :(得分:1)

该错误表示您尚未为未经身份验证的身份设置身份池,并且您未在凭据提供程序上正确设置Auth0 IdToken。

此博客可能会有所帮助 https://aws.amazon.com/blogs/mobile/using-amazon-cognito-with-swift-sample-app-developer-guide-and-more/