iOS Biometric Local Authentication

Shubham Jain
5 min readMar 11, 2018

+ShUBHAm JAin

Implement the TouchID Authentication

The TouchID/FaceID is a feature based on a framework called Local Authentication, which provides facilities for requesting authentication from users with specified security policies.

Local Authentication handles everything in context of handling the TouchID/FaceID while using in applications. It will prompt for authentication with custom message which will tell user why we need authentication, so users can place his finger on the home button.

Local Authentication framework

LocalAuthentication framework is used to implement the TouchID or FaceID authentication in the iOS Mobile Application.Use of touchId authentication is based on Local Authentication Framework.

To implement touchId feature first we ned to add LocalAuthentication framework in our project.

In the Project Navigation

-> select target -> go to build Phase ->click on Link binary with Libraries->Add Framework

Add LocalAuthentication Framework in Project Target

Now we are ready to write code. In the AppDelegate class import the LocalAuthentication.framework

using the below statement

@import LocalAuthentication;

Next Step is to ask framework that the touchID can be applied to a specific device by evaluate the policy function and it will accept two parameters one the policy name that we want to evaluate and second the error code.

Identify the following cases while implementing the TouchID in App:

Case 1 : Device is enabled with Biometric Sensor or not.
Case 2 : At Least one Fingerprint is enrolled in device or not to check Biometric sensor availability.

LAPolicy are of two types,

  1. deviceOwnerAuthenticationWithBiometrics: It puts restriction to use only biometric authentication to authenticate the device owner.

2. deviceOwnerAuthentication: It will allow the application to authenticate the device owner using biometric or the device password.

Case 1:

Case 2:

Biometric authentication dialog behaves similarly as the one used by LAPolicyDeviceOwnerAuthenticationWithBiometrics. However, instead of “Enter Password” button there is “Enter Passcode” button which, when tapped, switches the authentication method and allows users to enter device passcode.

NOTE:

Biometric authentication will get locked after 5 unsuccessful attempts. After that,users have to unlock it by entering passcode. The passcode can be entered either at Lock Screen or even in app by the means of LAPolicyDeviceOwnerAuthentication.The Lock Screen unlock is preferred user experience because we generaly don’t want users to enter their passcode at app’s request.

In AppDelegate First check device is enabled with biometry sensor and atleast one fingerprint is enrolled in devicewhen the app is launched at very first time

LAContext : An LAContext object represents an authentication context and provide a programmatic interface for evaluating authentication policies.

LAContext *context = [[LAContext alloc] init];
NSError *authError = nil;
Test if fingerprint authentication is available on
the device and a fingerprint has been enrolled.
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:HAS_DEVICE_ENROLLED_TOUCH_ID];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:HAS_DEVICE_BIOMETRY_SENSOR];
Biometric policy is successfully evaluated
device is enabled with Biometric sensor and
one fingerprint is enrolled in device.
}
else {
Could not evaluate policy;
look at authError and present an appropriate message to user
if(authError){
if (@available(iOS 11.0, *)) {
if(authError.code == LAErrorBiometryNotAvailable){
Device is not enable with Biometry sensor
on iOS version 11 onwards
}
else if(authError.code == LAErrorBiometryNotEnrolled){
Device is enable with Biometry sensor but
touchID is not enrolled in Device
}
}
else {
Fallback approach on earlier versions
if (authError.code == LAErrorTouchIDNotAvailable){
Device is not enable with Biometry sensor
on iOS version is below 11
}
else if(authError.code == LAErrorTouchIDNotEnrolled){
Device is enable with Biometry sensor but
touchID is not enrolled in Device
}
}
}
}
}

NOTE:

Before iOS 11 it was TouchIDLockout, touchIDNotAvailable, and touchIDNotEnrolled 
respectively.

In the ViewController class

First check device has biometry sensor or not in ViewDidLoad method .If yes, Show the biometry authentication option in application.

- (void)viewDidLoad
{
hasBiometrySensor = [[NSUserDefaults standardUserDefaults] boolForKey:HAS_DEVICE_BIOMETRY_SENSOR];
if(SHOW_FINGERPRINT_LOGIN && hasBiometrySensor){
[self.biometryView setHidden:NO];
}
else{
[self.biometryView setHidden:YES];
}
}

After that if device has biometry option and the touch ID is not registered in device then on touchButton tap ask user to enrolled the touchID in the device

-(void)setUPTouchIDInDevice{      UIAlertActionButton *button = [[UIAlertActionButton alloc] initWithTitle:@"OK"
style:UIAlertActionStyleDefault
andActionHandler:^{
NSURL *url = [NSURL URLWithString:@"App-Prefs:root=TOUCHID_PASSCODE"];
if([[UIApplication sharedApplication] canOpenURL:url]){
[[UIApplication sharedApplication] openURL:url];
NSLog(@"go to device settings to enroll fingerprint");
}
}];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Touch ID Setup"
message:@"Please setup Touch ID in your device"
actionButtons:@[button]
presentViewController:self
animation:YES
andCompletionHandler:nil];
[alert showOPActionAlert];
}

After enrolled the touchID in device ask user to enrolled touchID in the Application

-(void)enrolledTouchIDInAppliction{

LAContext *context = [[LAContext alloc] init];
NSError *authError = nil;

Test if fingerprint authentication is available
on the device and a fingerprint has been enrolled.

NSString *myLocalizedReasonString = @"Please authenticate using your fingerprint.";

if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {

[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics

localizedReason:myLocalizedReasonString

reply:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"User authenticated successfully, take appropriate action");
}
else {
NSLog(@"User did not authenticate successfully, look at error and take appropriate action");
if(error.code == -1){
NSLog(@"Application retry limit exceeded");
}
else if(error.code == LAErrorUserCancel){
NSLog(@"user has tapped the home button and authentication is canced by user");
}
if (@available(iOS 11.0, *)) {
if(error.code == LAErrorBiometryLockout){

NSLog(@"Authentication was not successful,
because there were too many failed biometry attempts(5 consequitive attempts)and biometry is now locked.Passcode is required to unlock biometry");
}
else if(error.code == LAErrorSystemCancel){
NSLog(@"Authentication was canceled by system (e.g. another application went to foreground).");
}
else if(error.code == LAErrorSystemCancel){
NSLog(@"Authentication was canceled by system (e.g. another application went to foreground).");
}
else {}
}
else {
// Fallback approach on earlier versions
if (error.code == LAErrorTouchIDLockout){

NSLog(@"Authentication was not successful,because there were too many failed biometry attempts and biometry is now locked.Passcode is required to unlock biometry");
}
else {}
}
}
}];
}
else {

if (authError.code) {

NSLog(@"There is no need to handle evaluate policy auth error as user is already handled the policy evaluated error in app delegate if user is not handling the policy evaluated error in app delegate then handle the auth error here.");
}
}
}

Once user enrolled the touch ID in application then user is able to perform task by using the fingerprint e.g login in app.

I have tried to create the high-level workflow for Biometric authentification, this also might help you guys to understand the workflow.

Thanks

If you liked this article, please follioowing me on Medium. When I have something new and awesome to share. It’s the best way to find out when I write more articles like this.

iOSBlogger : https://zenshubham.blogspot.com/2018/03/biometric-integration-in-ios-mobile.html

--

--