В AWS iOS SDK как мне обработать пользовательский статус FORCE_CHANGE_PASSWORD

Я следовал за примером здесь

https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoYourUserPools-Sample

Чтобы интегрировать интерактивный логин cognito в мое приложение iOS. Это все работает хорошо, но когда в пуле создается новый пользователь, он изначально имеет статус FORCE_CHANGE_PASSWORD.

Для Android вы можете следовать процедуре ниже

http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-android-sdk-authenticate-admin-created-user.html

Но для iOS я не могу узнать, как это сделать. Используя пример, если я пытаюсь войти в систему с пользователем в состоянии FORCE_CHANGE_PASSWORD, я вижу следующий вывод в журналах консоли (некоторые значения для краткости удалены):

{ "ChallengeName":"NEW_PASSWORD_REQUIRED", "ChallengeParameters": { "requiredAttributes":"[]", "userAttributes":"{\" email_verified \ ": \" истинным \",\"обычай:autoconfirm\":\"Y\","сессия":"хуг"}

Ниже приведен код из SignInViewController из примера, описанного выше.

import Foundation
import AWSCognitoIdentityProvider

class SignInViewController: UIViewController {
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    var passwordAuthenticationCompletion: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>?
    var usernameText: String?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.password.text = nil
        self.username.text = usernameText
        self.navigationController?.setNavigationBarHidden(true,   animated: false)
    }

    @IBAction func signInPressed(_ sender: AnyObject) {
        if (self.username.text != nil && self.password.text != nil) {
            let authDetails = AWSCognitoIdentityPasswordAuthenticationDetails(username: self.username.text!, password: self.password.text! )
            self.passwordAuthenticationCompletion?.set(result: authDetails)
        } else {
            let alertController = UIAlertController(title: "Missing information",
                                                message: "Please enter a valid user name and password",
                                                preferredStyle: .alert)
            let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
            alertController.addAction(retryAction)
        }
    }
}

extension SignInViewController: AWSCognitoIdentityPasswordAuthentication {

    public func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>)     {
        self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource
        DispatchQueue.main.async {
            if (self.usernameText == nil) {
                self.usernameText = authenticationInput.lastKnownUsername
            }
        }
    }

    public func didCompleteStepWithError(_ error: Error?) {
        DispatchQueue.main.async {
        if let error = error as? NSError {
            let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                                    message: error.userInfo["message"] as? String,
                                                    preferredStyle: .alert)
            let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
            alertController.addAction(retryAction)

            self.present(alertController, animated: true, completion:  nil)
            } else {
                self.username.text = nil
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}

когда didCompleteStepWithError выполняет, error является нулем, где я ожидал бы, чтобы это указывало на то, что говорит нам, что пользователь обязан сменить пароль.

Мой вопрос действительно, как поймать "ChallengeName":"NEW_PASSWORD_REQUIRED" json что выводится на консоль?

2 ответа

Решение

Сортировал это сейчас. Размещать это здесь на случай, если это поможет кому-то еще.

Во-первых, вам нужно создать контроллер представления, который позволит пользователю указать новый пароль. ViewController должен иметь AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails> как собственность:

var newPasswordCompletion: AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails>?

Следуя схеме в образце, указанном в вопросе, я затем реализовал AWSCognitoIdentityNewPasswordRequired как расширение для контроллера представления следующим образом:

extension NewPasswordRequiredViewController: AWSCognitoIdentityNewPasswordRequired {
    func getNewPasswordDetails(_ newPasswordRequiredInput: AWSCognitoIdentityNewPasswordRequiredInput, newPasswordRequiredCompletionSource:
    AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails>) {                    
        self.newPasswordCompletion = newPasswordRequiredCompletionSource
    }

    func didCompleteNewPasswordStepWithError(_ error: Error?) {
        if let error = error as? NSError {
            // Handle error
        } else {
            // Handle success, in my case simply dismiss the view controller
            self.dismiss(animated: true, completion: nil)
        }
    }

}

Снова следуя схеме образца, подробно изложенной в вопросе, добавьте функцию к AWSCognitoIdentityInteractiveAuthenticationDelegate расширение для AppDelegate:

extension AppDelegate: AWSCognitoIdentityInteractiveAuthenticationDelegate {
    func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication {
        //Existing implementation
    }
    func startNewPasswordRequired() -> AWSCognitoIdentityNewPasswordRequired {
        // Your code to handle how the NewPasswordRequiredViewController is created / presented, the view controller should be returned
        return self.newPasswordRequiredViewController!
    }
}

Прекрасный пример реализации ResetPassword при создании пользователя в Cognito Console.

Но интеграция этого механизма ResetPassword в существующее приложение является вашей ответственностью.

https://github.com/davidtucker/CognitoSampleApplication/tree/article1/CognitoApplication

Другие вопросы по тегам