如何从AWS Cognito获取用户名 - Swift

时间:2018-04-08 14:22:09

标签: swift username cognito

Q&风格:见下面的答案

如何从使用Cognito登录的用户获取用户名?

我已经完成了这个并且我的用户已登录,现在是什么?

AWSAuthUIViewController.presentViewController(
  with: self.navigationController!,
  configuration: config, completionHandler: { (provider: AWSSignInProvider, error: Error?) in
    if error == nil {          
      //get parameters
      }
    } else {
      print(error as Any)
    }
})

}

2 个答案:

答案 0 :(得分:6)

先决条件:

  • 在MobileHub注册的应用程序
  • MobileHub中的Cognito设置
  • Mobilehub使用AWS SDK与Swift Project集成

如果你像我一样,你做的很少甚至没有困难,现在你不得不尝试从登录用户那里获取用户名和其他参数。有很多答案,但到目前为止,我没有偶然发现一个可以让你一直到那里的答案。

我能够从各种来源把它拼凑起来:

   func getUsername() {
    //to check if user is logged in with Cognito... not sure if this is necessary
    let identityManager = AWSIdentityManager.default()
    let identityProvider = identityManager.credentialsProvider.identityProvider.identityProviderName

    if identityProvider == "cognito-identity.amazonaws.com" {
      print("************LOGGED IN WITH COGNITO************")
      let serviceConfiguration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: nil)
      let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YourClientID", clientSecret: "YourSecretKey", poolId: "YourPoolID")
      AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "YourPoolName (typically formatted as YourAppName_userpoool_MOBILEHUB_12345678")
      let pool = AWSCognitoIdentityUserPool(forKey: "YourPoolName")
      // the following line doesn't seem to be necessary and isn't used so I've commented it out, but it is included in official documentation
      //      let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: "YourPoolID", identityProviderManager:pool)          
      if let username = pool.currentUser()?.username {            
        print("Username Retrieved Successfully: \(username)")
      } else {
        print("Error getting username from current user - attempt to get user")
        let user = pool.getUser()            
        let username = user.username
        print("Username: \(username)")
      }
    }
  }

要获取您的ClientID,密钥和PoolID,请检查awsconfiguration.json

要获取您的PoolName,登录MobileHub,并在项目的后端,请转到“用户登录”,单击“电子邮件和密码”,然后单击“在Cognito中编辑”。以下页面将您的池名称设为“YourAppName_userpool_MOBILEHUB_12345678”

编辑:获取所有属性:

  if let userFromPool = pool.currentUser() {        
    userFromPool.getDetails().continueOnSuccessWith(block: { (task) -> Any? in
      DispatchQueue.main.async {

        if let error = task.error as NSError? {
          print("Error getting user attributes from Cognito: \(error)")
        } else {
          let response = task.result
          if let userAttributes = response?.userAttributes {
            print("user attributes found: \(userAttributes)")
            for attribute in userAttributes {
              if attribute.name == "email" {
                if let email = attribute.value {
                  print("User Email: \(email)")                      
                }
              }
            }

答案 1 :(得分:2)

如果您正在使用Cognito用户池,则可以使用以下方法:

import AWSUserPoolsSignIn

AWSCognitoUserPoolsSignInProvider.sharedInstance()
    .getUserPool()
    .currentUser()?
    .username