Implementing TouchID Authentication in iOS 10 Apps

From Techotopia
Jump to: navigation, search

PreviousTable of ContentsNext
An iOS 10 3D Touch Peek and Pop TutorialDrawing iOS 10 2D Graphics with Core Graphics


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book


In the world of computer security, user authentication falls into the three categories of something you know, something you have and something you are. The “something you know” category typically involves a memorized password or PIN number and is considered the least secure option. A more secure option is the “something you have” approach which usually takes the form of a small authentication token or device which generates one-time access codes on request.

The final category, “something you are”, refers to a physical attribute that is unique to the user. This, of course, involves biometrics in the form of a retina scan, voice recognition or fingerprint.

With the iPhone 5s, Apple introduced a built-in fingerprint scanner which enabled users to access the device and make purchases in the iTunes, App and iBooks stores using fingerprint authentication. Since the introduction of iOS 8, this biometric authentication capability can now be built into your own applications.




The Local Authentication Framework

TouchID based authentication for iOS applications is implemented using the Local Authentication Framework. The key class within this framework is the LAContext class which, among other tasks, is used to evaluate the authentication abilities of the device on which the application is running and perform the authentication.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Checking for TouchID Availability

Not all iOS devices have the fingerprint scanner and, even on devices with a scanner, not all users will have activated the TouchID authentication features. The first step in using TouchID authentication, therefore, is to check that TouchID authentication is a viable option on the device:

let context = LAContext()

var error: NSError?

if context.canEvaluatePolicy(
	LAPolicy.DeviceOwnerAuthenticationWithBiometrics, 
		error: &error) {
	// TouchID is available on the device
} else {
	// TouchID is not available on the device
	// No scanner or user has not set up TouchID
}

If TouchID authentication is not available, the reason can be identified by accessing the errorCode property of the error parameter and will fall into one of the following categories:

LAError.touchIDNotEnrolled – The user has not enrolled any fingerprints into TouchID on the device.

LAError.passcodeNotSet – The user has not yet configured a passcode on the device.

LAError.touchIDNotAvailable – The device does not have a TouchID fingerprint scanner.


Evaluating TouchID Policy

In the event that TouchID is available, the next step is to evaluate the policy (which in terms of TouchID involves prompting the user to provide authentication). This task is performed by calling the evaluatePolicy method of the LAContext instance, passing through the authentication policy type and a message to be displayed to the user. The task is performed asynchronously and a reply closure expression called once the user has provided input:

context.evaluatePolicy(
	LAPolicy.deviceOwnerAuthenticationWithBiometrics, 
	localizedReason: "Authentication is required for access", 
	reply: {(success, error) in
		// Code to handle reply here
  })

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

The reply closure expression is passed a Boolean value indicating the success or otherwise of the authentication and an NSError object from which the nature of any failure can be identified via the corresponding error code. Failure to authenticate will fall into one of the following three categories:

LAError.systemCancel – The authentication process was cancelled by the operating system. This error typically occurs when the application is placed in the background.

LAError.userCancel - The authentication process was cancelled by the user.

LAError.userFallback – The user opted to authenticate using a password instead of using TouchID.

In the event of the user fallback, it is the responsibility of the application to prompt for and verify a password before providing access.

If the authentication process is successful, however, the application should provide the user with access to whatever screens, data or functionality were being protected.

A TouchID Example Project

Launch Xcode and create a new iOS Universal Single View Application project named TouchID using Swift as the programming language. Select the Main.storyboard file and drag and drop a Button view so that it is positioned in the center of the storyboard scene. Double-click on the button and change the text so that it reads “Test TouchID”. With the button still selected, display the Auto Layout Align menu and configure both horizontal and vertical center in container constraints.

Finally, display the Assistant Editor and Ctrl-click and drag from the button view to a position just beneath the viewDidLoad method in the ViewController.swift file. Release the line and, in the connection dialog, establish an Action connection to a method named testTouchID.

On completion of the user interface design the layout should resemble Figure 60-1:

The user interface for the example TouchID iOS app

Figure 60-1

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Checking for TouchID Availability

With the user interface designed, the next step is to add some code to the testTouchID function to verify that the device can handle TouchID authentication. Select the ViewController.swift file, import the LocalAuthentication Framework and add code to the testTouchID method as follows:

import UIKit
import LocalAuthentication

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func testTouchID(_ sender: AnyObject) {

        let context = LAContext()

        var error: NSError?

        if context.canEvaluatePolicy(
                LAPolicy.deviceOwnerAuthenticationWithBiometrics,
                        error: &error) {

              // Device can use TouchID

        } else {
            // Device cannot use TouchID
            switch error!.code{

            case LAError.Code.touchIDNotEnrolled.rawValue:
                notifyUser("TouchID is not enrolled",
                        err: error?.localizedDescription)

            case LAError.Code.passcodeNotSet.rawValue:
                notifyUser("A passcode has not been set",
                        err: error?.localizedDescription)

            default:
                notifyUser("TouchID not available",
                        err: error?.localizedDescription)

            }
        }    
    }
.
.
}

Before proceeding, implement the notifyUser method as follows:

func notifyUser(_ msg: String, err: String?) {
    let alert = UIAlertController(title: msg, 
		message: err, 
		preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "OK", 
		style: .cancel, handler: nil)

    alert.addAction(cancelAction)

    self.present(alert, animated: true,
                        completion: nil)
}

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Seeking TouchID Authentication

The next task is to attempt to obtain authentication from the user. This involves a call to the evaluatePolicy method of the local authentication context:

@IBAction func testTouchID(_ sender: AnyObject) {

    let context = LAContext()

    var error: NSError?

    if context.canEvaluatePolicy(
	LAPolicy.DeviceOwnerAuthenticationWithBiometrics, 
		error: &error) {

        // Device can use TouchID

            context.evaluatePolicy(
                LAPolicy.deviceOwnerAuthenticationWithBiometrics,
                localizedReason: "Access requires authentication",
                        reply: {(success, error) in
                DispatchQueue.main.async {

                    if error != nil {

                        switch error!._code {

                            case LAError.Code.systemCancel.rawValue:
                                self.notifyUser("Session cancelled",
                        err: error?.localizedDescription)

                            case LAError.Code.userCancel.rawValue:
                            self.notifyUser("Please try again",
                          err: error?.localizedDescription)

                            case LAError.Code.userFallback.rawValue:
                                self.notifyUser("Authentication",
                        err: "Password option selected")
                                // Custom code to obtain password here

                            default:
                                self.notifyUser("Authentication failed",
                        err: error?.localizedDescription)
                        }

                    } else {
                        self.notifyUser("Authentication Successful",
                    err: "You now have full access")
                    }
                }
            })
    } else {
        // Device cannot use TouchID
.
.
.

    }
}

The code added to the method initiates the authentication process and displays a message confirming a successful authentication. In the event of an authentication failure, a message is displayed to the user indicating the reason for the failure. Selection of the password option simply confirms that the option was selected. The actual action taken in this situation will be application specific but will likely involve prompting for a password and verifying it against a database of valid passwords.

You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book

Testing the Application

Compile and run the application on a physical iOS device (TouchID is not available on the simulator environment) and tap on the Test TouchID button. If the device supports TouchID and has been enabled and configured by the user, the touch request panel will appear as demonstrated in Figure 60-2:


Ios 8 touchid panel.png

Figure 60-2

Authenticate with a registered fingerprint and wait for the confirmation of successful authentication to appear. Experiment with a variety of failure scenarios to verify that the error handling code covers all events (such as tapping the Cancel button or attempting to authenticate with a non-registered fingerprint).

Summary

Introduced with iOS 7 and the iPhone 5s device, TouchID has been provided to iOS users as a way to gain access to devices and to make Apple related purchases. Since the introduction of iOS 8, fingerprint authentication using the TouchID system is now available to application developers. This chapter has outlined the steps involved in using the Local Authentication Framework to implement biometric authentication using the TouchID system.


You are reading a sample chapter from the iOS 10 App Development Essentials book.

Purchase the full iOS 10 / Swift 3 / Xcode 8 edition of this book in eBook ($19.99) or Print ($45.99) format.
iOS 10 App Development Essentials Print and eBook (ePub/PDF/Kindle) edition contains over 100 chapters. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
An iOS 10 3D Touch Peek and Pop TutorialDrawing iOS 10 2D Graphics with Core Graphics