Swift 4-重新认证FaceID

时间:2019-04-30 15:49:31

标签: ios swift

我已经在我的应用上实现了Face ID身份验证,并且用户在点击按钮时会获得身份验证。我还实现了一种注销用户的注销方法:

dismiss(animated: true, completion: {

UserDefaults.standard.set(false, forKey: "hasLoginKey")

})

但是,当我注销然后尝试重新登录时,系统不会提示我输入FaceID,而是跳过了它,并且我已完全登录。我的问题是如何防止这种情况发生,并在用户每次点击按钮时提示用户登录?

这是按钮代码:

@IBAction func loginButtonPressed(_ sender: Any) {

        //Define Button variable from the button that has been tapped.
        let button = sender as! UIButton

        //If the button tag is Touch ID, authenticate the user

        if(button.tag == loginWithTouchID)
        {
            //Check if device is compatible with Touch ID
            if(touchMe.canEvaluatePolicy())
            {
                //Get Response from Touch ID popup
                touchMe.authenticateUser() { responsCode in

                    if let responsCode = responsCode {

                        if(responsCode == 0)
                        {
                            //If Touch ID is not available
                            self.customAlert(title: "Error", message: "Touch ID not available")
                        }
                        else if(responsCode == 1)
                        {
                            //If Touch ID has not been setup
                            self.customAlert(title: "Error", message: "Touch ID may not be configured")
                        }
                        else if(responsCode == 2)
                        {
                            //If Touch ID authentication failed
                            self.customAlert(title: "Error", message: "There was a problem verifying your identity")
                        }

                    } else {

                        //If there is no response code, that means Touch ID was successful in authenticating user and we can now call the login method
                        Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(Login.login), userInfo: nil, repeats: false)
                    }
                }
            }
        }
        else
        {
            Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(Login.login), userInfo: nil, repeats: false)
        }


    }

和我的TouchIDAuth类

class TouchIDAuth {

    let context = LAContext()

    func canEvaluatePolicy() -> Bool {
        return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
    }

    func authenticateUser(completion: @escaping (NSNumber?) -> Void) {

        guard canEvaluatePolicy() else {
            completion(0)
            return
        }

        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Logging in with Touch ID") { (success, evaluateError) in
            if success {
                DispatchQueue.main.async {
                    completion(nil)
                }
            } else {

                let response: NSNumber

                switch evaluateError?._code {
                case Int(kLAErrorAuthenticationFailed):
                    response = 2
                case Int(kLAErrorUserCancel):
                    response = 3
                case Int(kLAErrorUserFallback):
                    response = 4
                default:
                    response = 1
                }

                completion(response)

            }
        }
    }

}

这是在按下按钮的方法中调用的登录方法

@objc func login() {

        //Start Activity Indicator

        self.createIndicator()

        //Define Username and Password Variables

        var user: String!
        var pass: String!


        //Check if User is Authenticating with TouchID, we do this so we know to use credentials from Keychain to make the API call with
        if(loginButton.tag == loginWithTouchID)
        {
            //If Yes, Get the username from Keychain
            if let storedUsername = UserDefaults.standard.value(forKey: "username") as? String {

                //Get Password from Keychain

                do {

                    let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName,
                                                            account: storedUsername,
                                                            accessGroup: KeychainConfiguration.accessGroup)
                    let keychainPassword = try passwordItem.readPassword()

                    //Store Username and Password from Keychain into Username and Password variables

                    user = storedUsername
                    pass = keychainPassword

                }
                catch {

                    //If something went wrong, stop the Activity Indicator and Alert the user something went wrong.

                    self.stopIndicator()

                    self.customAlert(title: "Error", message: "Error reading password from keychain - \(error)")
                }

            }
        }
        else
        {
            //If we are not using Touch ID, store the username and password text field into the username and password variable to use for the API Call

            user = username.text!
            pass = password.text!
        }

        //Finally call the webservice

        WebService().loginUser(user, password: pass)
        {
            (result: Bool) in
            //If API call is successful
            if(result == true)
            {

                //Stop Activity Indicator

                self.stopIndicator()

                //Check if button tag is create, login or touch ID

                if self.loginButton.tag == self.createLoginButtonTag {

                    //If create, check if a user has login

                    let hasLoginKey = UserDefaults.standard.bool(forKey: "hasLoginKey")
                    if !hasLoginKey {

                        //If not, add username to App Default

                        UserDefaults.standard.setValue(user, forKey: "username")
                    }

                    //Try and save the password to Keychain

                    do {

                        //Create a KeychainPasswordItem

                        let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: user!, accessGroup: KeychainConfiguration.accessGroup)

                        //Save password to the new KeychainPasswordItem

                        try passwordItem.savePassword(pass!)

                        //Add hasLoginKey bool to App Defaults

                        UserDefaults.standard.set(true, forKey: "hasLoginKey")

                        //Change Login button tag to Login as we do not need to create this user again

                        self.loginButton.tag = self.loginButtonTag

                        //Store Credentials to App Delegate to make API calls down the road.

                        self.appDelegate.username = user
                        self.appDelegate.password = pass

                        self.password.text = ""

                        //Everything has been authenticated, proceed to Dashboad

                        self.performSegue(withIdentifier: "toolbarSegue", sender: nil)


                    } catch {

                        //Something went wrong, alert the user with error.

                        self.customAlert(title: "Error", message: "Error updating keychain - \(error)")

                    }

                }
                    //If Login Button tag with Login
                else if self.loginButton.tag == self.loginButtonTag {

                    //Check if user exists in Keychain

                    if self.checkLogin(username: user, password: pass) {

                        //Store Credentials to App Delegate to make API calls down the road.

                        self.appDelegate.username = user
                        self.appDelegate.password = pass

                        self.password.text = ""

                        //Exisiting user has been authenticated, proceed to Dashboad

                        self.performSegue(withIdentifier: "toolbarSegue", sender: nil)

                    } else {

                        //User does not exist in Keychain, alert user there is an error.

                        self.customAlert(title: "Login Problem", message: "Sorry Login Failed, User and/or Passsword Incorrect")
                    }

                }
                    //If Login Button tag with Touch ID
                else if self.loginButton.tag == self.loginWithTouchID {

                    //Store Credentials to App Delegate to make API calls down the road.

                    self.appDelegate.username = user
                    self.appDelegate.password = pass

                    self.password.text = ""

                    //Touch ID has been authenticated, proceed to Dashboad

                    self.performSegue(withIdentifier: "toolbarSegue", sender: nil)

                }

            }
            else
            {

                //Stop Activity Indicator

                self.stopIndicator()

                //API call was unsuccessful, alert user.

                self.customAlert(title: "Login Problem", message: "Sorry Login Failed, User and/or Passsword Incorrect")

            }

        }


    }

3 个答案:

答案 0 :(得分:2)

我认为您正在const rectNode:any = this.createSvgElem('rect', { 'x': options.bbox[0], 'y': options.bbox[1], 'width': options.bbox[2] - options.bbox[0], 'height': options.bbox[3] - options.bbox[1], 'id': node.id, 'bbox': node.title, 'class': className }); parentRectsNode.appendChild(rectNode); // cross-link both nodes: rectNode.linkedNode = node; node.linkedNode = rectNode; } 的这一行中跟踪登录按钮标记:

login

这就是为什么当用户下次单击登录按钮时,它将直接对用户进行身份验证(因为条件是//Change Login button tag to Login as we do not need to create this user again, as you have specified self.loginButton.tag = self.loginButtonTag ):

false

所以我认为您不应该更改 if(button.tag == loginWithTouchID) { // login with touchID else { // authenticate the user }

答案 1 :(得分:0)

注意:根据您的问题

但是,当我注销然后尝试重新登录时,系统不会提示我输入FaceID,而是跳过了它,并且我已完全登录。

通常,当您更新UserDefaults时(即针对键设置新值/对象),您确实添加了以下代码以使更改生效。

UserDefaults.standard.syncronize()

因此,请在

之后添加
UserDefaults.standard.set(false, forKey: "hasLoginKey") // 1


UserDefaults.standard.setValue(user, forKey: "username") // 2


UserDefaults.standard.set(true, forKey: "hasLoginKey") // 3

希望有帮助。

答案 2 :(得分:0)

我还实现了一种注销用户的注销方法:

dismiss(动画:true,完成:{

UserDefaults.standard.set(false,forKey:“ hasLoginKey”)

})

我的应用具有相同的行为。提示一次进行FaceID身份验证,而不是注销后提示。

如@Pranav Kasetti所述,在注销方法中添加TouchIDAuth.context = LAContext()(将其更改为var),如@Pranav Kasetti所述,身份验证上下文将重新初始化,并且将再次提示您的用户使用FaceID(或TouchID)。