Swift 4 - 重新验证 FaceID

Posted

技术标签:

【中文标题】Swift 4 - 重新验证 FaceID【英文标题】:Swift 4 - Re-Authenticate FaceID 【发布时间】:2019-04-30 15:49:30 【问题描述】:

我已经在我的应用程序上实现了 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")

            

        


    

【问题讨论】:

您是否将loginButtonPressed 函数用于另一个按钮? 对于另一种方法是的,我现在发布该方法。 上下文策略评估正在被重用,因为您使用的是相同的LAContext。重新初始化上下文以解决您的问题 【参考方案1】:

我认为您正在更改 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

所以我认为你不应该更改self.loginButton.tag

【讨论】:

【参考方案2】:

注意:鉴于您的问题

但是,当我注销然后尝试重新登录时,系统不会提示我输入 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

希望对你有帮助。

【讨论】:

Apple's documentation 说“这种方法是不必要的,不应该使用”。【参考方案3】:

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

解雇(动画:真,完成:

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

)

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

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

【讨论】:

以上是关于Swift 4 - 重新验证 FaceID的主要内容,如果未能解决你的问题,请参考以下文章

iPad也使用全面屏设计搭载faceID

无法重新授权用户更改电子邮件或重置密码(Firebase .. Swift)

有没有办法在 Swift Playgrounds 4 中重新缩进线条?

如何以编程方式根据排序标准对单元格重新排序 SWIFT 4

如何在swift 4中重新排序单元格后保存tableView顺序

是否可以重置应用程序的 Face ID 权限警报?