使用自訂挑戰的AWS Cognito用戶池與iOS的Mobile SDK


我最近將一個AWS Cognito用戶池整合到一個iOS應用程式中。登入功能使用自訂挑戰進行認證。然而,關於如何使用iOS SDK達到此目的的文件資料很有限。在多次嘗試和失敗後,我終於成功登入。以下是達成此目的的步驟:

步驟1:建立一個CognitoUserPool

AppDelegate中,完成didFinishLaunchingWithOptions後,用戶池如下所示初始化:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  // Set up service configuration
  let serviceConfiguration = AWSServiceConfiguration(region: CognitoIdentityUserPoolRegion, credentialsProvider: nil)

  // Create pool configuration
  let poolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: CognitoIdentityUserPoolAppClientId, clientSecret: nil, poolId: CognitoIdentityUserPoolId)

  // Initialize user pool client
  AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: poolConfiguration, forKey: AWSCognitoUserPoolsSignInProviderKey)

  // Fetch the user pool client we initialized in the above step
  let pool = AWSCognitoIdentityUserPool(forKey: AWSCognitoUserPoolsSignInProviderKey)

  self.storyboard = UIStoryboard(name: "Main", bundle: nil)

  pool.delegate = self

  return true
}

步驟2:執行協定代表

extension AppDelegate: AWSCognitoIdentityCustomAuthentication {

  func didCompleteStepWithError(_ error: Error?) {

  }

  func getCustomChallengeDetails(_ authenticationInput: AWSCognitoIdentityCustomAuthenticationInput, customAuthCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails>) {

  }

  func startCustomAuthentication() -> AWSCognitoIdentityCustomAuthentication {
    if self.navigationController == nil {
      self.navigationController = self.storyboard?.instantiateViewController(withIdentifier: "signinController") as? UINavigationController
    }

    if self.signInViewController == nil {
      self.signInViewController = self.navigationController?.viewControllers[0] as? SignInViewController
    }

    DispatchQueue.main.async {
      self.navigationController!.popToRootViewController(animated: true)

      if !self.navigationController!.isViewLoaded || self.navigationController!.view.window == nil {
        self.window?.rootViewController?.present(self.navigationController!, animated: true, completion: nil)
      }
    }

    return self.signInViewController!
  }
}

步驟3:在登入視圖控制器中處理自訂挑戰

extension SignInViewController: AWSCognitoIdentityCustomAuthentication {

  func getCustomChallengeDetails(_ authenticationInput: AWSCognitoIdentityCustomAuthenticationInput, customAuthCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityCustomChallengeDetails>) {

    let authDetails = AWSCognitoIdentityCustomChallengeDetails(challengeResponses: ["USERNAME": "YourUserName", "ANSWER": "123456"])
    customAuthCompletionSource.set(result: authDetails)
  }

  public func didCompleteStepWithError(_ error: Error?) {
    DispatchQueue.main.async {
      if let error = error as? NSError {
        print("error")
      } else {
        print("success")
        self.dismiss(animated: true, completion: nil)
      }
    }
  }
}

步驟4:成功登入後存取用戶屬性

self.user?.getDetails().continueOnSuccessWith { (task) -> AnyObject? in
  DispatchQueue.main.async(execute: {
    self.response = task.result

    // Display user details
    print(response)
  })

  return nil
}

如果你有任何問題,請隨時提問。我希望AWS能更新文檔,並提供範例代碼,以便在不需要透過試驗和錯誤的情況下理解SDK。