Use Apple FaceID or TouchID authentication in your app using BiometricAuthentication.

Overview

BiometricAuthentication

Use Apple FaceID or TouchID authentication in your app using BiometricAuthentication. It's very simple and easy to use that handles Touch ID and Face ID authentication based on the device.

Note: - Face ID authentication requires user's persmission to be add in info.plist.

<key>NSFaceIDUsageDescription</key>
<string>This app requires Face ID permission to authenticate using Face recognition.</string>

What's new in version 3.1

  • Updated to Swift 5.0
  • Implemented Result type as completion callback

Version 2.2

  • Set AllowableReuseDuration (in seconds) to auto authenticate when user has just unlocked the device with biometric.
  • This is pretty useful when app comes to foreground or device is just unlocked by the user and you want to authenticate with biometrics.
  • If you don't want to reuse the recently used authentication then simply skip this step.
// set this before calling authenticateWithBioMetrics method (optional)
BioMetricAuthenticator.shared.allowableReuseDuration = 60

Version 2.1

  • Check if TouchID or FaceID authentication is available for iOS device.

Alt text Alt text Alt text

Features

  • Works with Apple Face ID (iPhone X, Xs, XR, XsMax) and other Touch ID having devices.
  • Predefined error handling when recognition fails.
  • Automatic authentication with device passcode on multiple failed attempts.

Requirements

  • iOS 12.0+
  • Xcode 10+
  • Swift 3.0+

Installation

CocoaPods

pod 'BiometricAuthentication'

Carthage

github "rushisangani/BiometricAuthentication"

Usage

Authenticate with biometric

BioMetricAuthenticator.authenticateWithBioMetrics(reason: "") { (result) in

    switch result {
    case .success( _):
        print("Authentication Successful")
    case .failure(let error):
        print("Authentication Failed")
    }
}
  • When reason specified as empty - default will be used based on the device. Ex. for iPhone X - "Confirm your face to authenticate.", For other devices - "Confirm your fingerprint to authenticate."

Can Authenticate with biometric

  • Alternatively you can check before authentication by following. This will check that if device supports Touch ID or Face ID authentication and your app can use that as of now.
if BioMetricAuthenticator.canAuthenticate() {

    BioMetricAuthenticator.authenticateWithBioMetrics(reason: "") { (result) in
        // check result -> success or failure
    }
}

Check for Face ID

  • Check if device supports face recognition or not.
if BioMetricAuthenticator.shared.faceIDAvailable() {
    // device supports face id recognition.
}

Check for Touch ID

  • Check if device supports touch id authentication or not.
if BioMetricAuthenticator.shared.touchIDAvailable() {
    // device supports touch id authentication
}

Fallback Reason

  • Fallback reason title will be shown when first authentication attempt is failed.
  • You can give alternate authentication options like enter 'username & password' when user clicks on fallback button.
  • Default reason is empty, which will hide fallback button.
BioMetricAuthenticator.authenticateWithBioMetrics(reason: "Biometric Authentication", fallbackTitle: "Enter Credentials") { (result) in

    switch result {
    case .success( _):
        // proceed further

    case .failure(let error):

        switch error {
        case .fallback:

            print("Authentication Failed")

            // show alternatives on fallback button clicked
            // for ex. - enter username/email and password

        default:
            break
        }
    }
}

BiometryLockedout

  • When biometry authentication is locked out after multiple failed attempts. You can unlock it by passcode authentication.
  • Provide your own passcode authentication reason here, default will be used if not provided.
BioMetricAuthenticator.authenticateWithPasscode(reason: message) { (result) in
    switch result {
    case .success( _):
        // passcode authentication success
    case .failure(let error):
        print(error.message())
    }
}

Error Handling

  • There are various cases when biometric authentication can be failed.
  1. fallback
    • Called when user clicks on provided fallback button.
  2. biometryNotEnrolled
    • Called when no fingerprints or face is registered with the device.
    • You can show message to register a new face or fingerprint here.
    • Default message will be shown if not provided.
  3. canceledByUser
    • Called when authentication canceled by user.
  4. canceledBySystem
    • Called when authentication canceled by system when app goes into background or any other reason.
  5. passcodeNotSet
    • Called when device passcode is not set and trying to use biometry authentication.
    • We can ask user to set device passcode here by opening Settings Application.
  6. failed
    • Called when multiple failed attempts made by user.
    • You can show error message to user here.
    • Default message can be shown if not provided.
  7. biometryLockedout
    • Called when more than 5 failed attempts made using biometric authentication. This will locked your biometry system.
    • You'll restrict user when this error is occured.
    • Aleternatively you can ask user to enter device passcode to unlock biometry.
  8. biometryNotAvailable
    • Called when device does not support Face ID or Touch ID authentication.

Example

BioMetricAuthenticator.authenticateWithBioMetrics(reason: "") { [weak self] (result) in

    switch result {
    case .success( _):

        // authentication successful
        self?.showLoginSucessAlert()

    case .failure(let error):

        switch error {

        // device does not support biometric (face id or touch id) authentication
        case .biometryNotAvailable:
            self?.showErrorAlert(message: error.message())

        // No biometry enrolled in this device, ask user to register fingerprint or face
        case .biometryNotEnrolled:
            self?.showGotoSettingsAlert(message: error.message())

        // show alternatives on fallback button clicked
        case .fallback:
            self?.txtUsername.becomeFirstResponder() // enter username password manually

        // Biometry is locked out now, because there were too many failed attempts.
        // Need to enter device passcode to unlock.
        case .biometryLockedout:
            self?.showPasscodeAuthentication(message: error.message())

        // do nothing on canceled by system or user
        case .canceledBySystem, .canceledByUser:
            break

        // show error for any other reason
        default:
            self?.showErrorAlert(message: error.message())
        }
    }
}

See Example for more details.

License

BiometricAuthentication is released under the MIT license. See LICENSE for details.

Comments
  • Changing the logic of allowableReuseDuration property

    Changing the logic of allowableReuseDuration property

    There are 2 issues when using allowableReuseDuration:

    • value 0 is not equal to disabling the property;
    • only one instance of LAContext is uses.

    It can get trouble for example in situation when I set allowableReuseDuration and start scanning a lot of times - each next scanning will use the first result.

    Could you change the logic of allowableReuseDuration?

    • remove optional type (from TimeInterval? to TimeInterval);
    • add the default value 0 to allowableReuseDuration;
    • remove didSet handler from allowableReuseDuration;
    • set the touchIDAuthenticationAllowableReuseDuration property right after LAContext creation.

    For example

    var allowableReuseDuration: TimeInterval = 0
    
    // context
    let context = LAContext()
    context.touchIDAuthenticationAllowableReuseDuration = allowableReuseDuration
    
    opened by lmvdev 9
  • Issue in BiometricAuthentication

    Issue in BiometricAuthentication

    Hi, thx for this pod it is very useful. I tested on Xcode 9.2 and swift version 4.0. I found error in public func faceIDAvailable(). I think it might be like this:

    public func faceIDAvailable() -> Bool { if #available(iOS 11.0, *) { let context = LAContext() return (context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil) && context.biometryType == LABiometryType.faceID) } return false }

    opened by nikolovnikos 9
  • Error while installing with CocoaPods

    Error while installing with CocoaPods

    Hi Rushi, first of all, great work. I tried to install it using CocoaPods and it's giving me this error.

    Specs satisfying the BiometricAuthentication (= 1.0.0) dependency were found, but they required a higher minimum deployment target.

    For my app, the deployment target is 9.0.

    I need to ask you whether it will work with 9.0 or not? And if not, if I change my deployment target to 10.0 will my app install on the devices having lesser than 10.0?

    opened by hemangshah 9
  • BiometicAuthentication Xcode 10 beta 1 compile error.

    BiometicAuthentication Xcode 10 beta 1 compile error.

    BioMetricAuthenticator.swift

    let errorType = AuthenticationError(error: err as! LAError) has error: 'AuthenticationError' cannot be constructed because it has no accessible initializers

    opened by johnlietzke 8
  • How to force set TouchID over FaceID usage?

    How to force set TouchID over FaceID usage?

    I am now using BiometricAuthentication in my app. And right now, I don't have an iPhone X device to test this. So is there a way that I can tell BiometricAuthentication to use TouchID only? Or in other words, I don't have a requirement to use FaceID as of now so want to use their TouchID only.

    opened by hemangshah 8
  • Undeclared type Result error prompt

    Undeclared type Result error prompt

    Use of undeclared type 'Result'

    class func authenticateWithBioMetrics(reason: String, fallbackTitle: String? = "", cancelTitle: String? = "", completion: @escaping (Result<Bool, AuthenticationError>) -> Void) { from class BioMetricAuthenticator

    opened by arishanapalli 6
  • TouchID 'remembered' even with allowableReuseDuration = 0

    TouchID 'remembered' even with allowableReuseDuration = 0

    Hello BiometricAuthentication users,

    I use this nice SDK in an iOS project (XCode 10.1, Swift 4). Even when I set allowableReuseDuration = 0, the touchID is remembered by the device and not requested again. Any idea what could be the cause of this ?

    Thanks for any advice Frank

    opened by fvvliet 5
  • touchIDAvailable()

    touchIDAvailable()

    Hello,

    I think it would be useful to be able to see if touch id is available for devices that may not support the option or I believe if the device has touch id but is turned off, LAContext returns false. It would basically be a copy of faceIDAvailable() function just swapped with touchID biometric type. If you need me to create a pull request I can help out.

    Thanks Joe

    opened by gintechsystems 4
  • An instance of LAContext can't determine biometryType until canEvaluatePolicy has been called

    An instance of LAContext can't determine biometryType until canEvaluatePolicy has been called

    It seems like your faceIDAvailable function will always fail because you don't call canEvaluatePolicy on the LAContext instance object before checking the biometry type.

    Something like this should help:

    public func faceIDAvailable() -> Bool {
            if #available(iOS 11.0, *) {
                let context = LAContext()
                return (context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) && LAContext().biometryType == .typeFaceID)
            }
            return false
        }
    

    Here's the apple doc describing the biometryType instance property: https://developer.apple.com/documentation/localauthentication/lacontext/2867583-biometrytype

    opened by Chris-Corea 4
  • Show correct message when biometry is not enrolled

    Show correct message when biometry is not enrolled

    .faceIDAvailable() always returns false if biometry is not enrolled which results in the TouchID message being shown regardless of device. This PR patches that bug without changing the existing functionality of .faceIDAvailable() so as not to introduce a potentially breaking change.

    Reproduction Steps:

    • Run the example app on a simulator that supports FaceID
    • Disable biometrics by deselecting Hardware > Face ID > Enrolled
    • Tap the "Biometric authentication" button in the example app

    Observe: An alert prompts the user to enroll their fingerprints for Touch ID Expected: An alert prompts the user to enroll their face for Face ID

    opened by Sidetalker 3
  • Framework not compatible for iOS-13 [Enhancement]

    Framework not compatible for iOS-13 [Enhancement]

    While building the application in Xcode 11-beta, we are facing the following issue by the compiler:

    Module compiled with Swift 5.0.1 cannot be imported by the Swift 5.1 compiler

    Can you please check and try to resolve so that we can fix it in our project as well.

    Framework with Swift version: [5.0.1] Xcode version: [11.0 beta-2] Your application language: [Swift-5.1]

    opened by akshardarji 3
  • BiometricAuthentication not working after Xcode and MAC update

    BiometricAuthentication not working after Xcode and MAC update

    BiometricAuthentication is giving errors when creating the build. It just says library not found in the errors. Recently I had updated the Xcode version to version 13.3 and MAC version 12.3.1

    After this update the errors started coming up. Can someone please help me on this ?

    opened by nishanega 0
  • Check for biometric authentication not working properly.

    Check for biometric authentication not working properly.

    After updating Xcode to latest version, authenticateWithBioMetrics function is not working as expected and it always returning biometryNotAvailable case when user doesn't allow the permission.

    Below screenshot is iPhone11(13.7) simulator.

    Simulator Screen Shot - iPhone 11 - 2020-09-22 at 07 52 15

    opened by saikumar-osv 1
Releases(v3.1.3)
Owner
Rushi Sangani
iOS Developer | Open-source Contributor | Software Engineer
Rushi Sangani
The TouchID authentication mechanism implemented in Swift.

iOS-TouchID-Swift The TouchID authentication mechanism implemented in Swift About In iOS 8, Apple provides a new framework named LocalAuthentication w

Gabriel Theodoropoulos 24 May 20, 2018
An iOS passcode lock with TouchID authentication written in Swift.

PasscodeLock A Swift implementation of passcode lock for iOS with TouchID authentication. Installation PasscodeLock requires Swift 2.0 and Xcode 7 Car

Yanko Dimitrov 679 Nov 26, 2022
An iOS passcode lock with TouchID authentication written in Swift.

PasscodeLock A Swift implementation of passcode lock for iOS with TouchID authentication. Originally created by @yankodimitrov, hope you're doing well

Serge Velikan 203 Dec 6, 2022
TouchID used easy on one line in your ViewController.

TouchIDExtension TouchID used easy on one line in your ViewController. ##Installation At this moment, You can install only a way, manually. For instal

Joan Molinas 65 Feb 26, 2020
TouchEncryptedJson - Simple project that accepts an input and encrypts it with the TouchID on a Mac

TouchEncryptedJson Simple project that accepts an input and encrypts it with the

Charles Edge 2 Aug 29, 2022
An easy-to-use, open-source two-factor authentication app designed specifically for iOS.

Tofu An easy-to-use, open-source two-factor authentication app designed specifically for iOS. Tofu generates one-time passwords to help you protect yo

Calle Luks 380 Jan 8, 2023
LocalAuth - Another Fusion library to implement the local authentication using Biometry

FusionLocalAuth Another Fusion library to implement the local authentication usi

Vedant Jha 0 Jan 13, 2022
The minimalistic, secure and open-source two-factor authentication app.

Einmal /ˈainmaːl/ German: once The minimalistic, secure and open-source two-factor authentication app. Features ♻️ Cross-platform — available on Andro

Incipher 75 Aug 21, 2022
Very simple swift wrapper for Biometric Authentication Services (Touch ID) on iOS.

SimpleTouch Very simple swift wrapper for Biometric Authentication Services (Touch ID) on iOS. Sample Project There is a SimpleTouchDemo target define

Simple Machines 117 Nov 15, 2022
Two-Factor Authentication Client for iOS

Authenticator Two-Factor Authentication Client for iOS. Authenticator is a simple, free, and open source two-factor authentication app. It helps keep

Matt Rubin 770 Dec 30, 2022
A privacy-focused app using Apple's soon-to-be-released contact tracing framework.

A privacy-focused app using Apple's soon-to-be-released contact tracing framework.

Crunchy Bagel Pty Ltd 350 Oct 16, 2022
A tiny and easy to use Swift class to encrypt strings using HMAC algorithms.

#Sweet HMAC SweetHMAC is a tiny and easy to use Swift class to encrypt strings using HMAC algorithms. A special thanks to jernejstrasner for shared HM

Jan Cássio 37 Jul 27, 2022
PGPro can encrypt and decrypt messages as well as manage all your OpenPGP keys. It is free, simple and lightweight. Everything stays on your device. PGPro is made in Switzerland.

PGPro can encrypt and decrypt messages as well as manage all your OpenPGP keys. It is free, simple and lightweight. Everything stays on your device. P

Luca Näf 250 Jan 4, 2023
Helps you define secure storages for your properties using Swift property wrappers.

?? Secure Property Storage Helps you define secure storages for your properties using Swift property wrappers. ?? Features All keys are hashed using S

Alex Rupérez 443 Jan 4, 2023
A wrapper for Apple's Common Crypto library written in Swift.

IDZSwiftCommonCrypto A Swift wrapper for Apple's CommonCrypto library. IDZSwiftCommonCrypto works with both CocoaPods and Cathage. For more details on

idz 472 Dec 12, 2022
Apple's iOS Private Frameworks

iOS Private Framework This repo contains reversed-engendered private frameworks used by Apple in iOS. Private frameworks are frameworks which you are

Reels Research, Inc. 8 Oct 25, 2022
Safe and easy to use crypto for iOS and macOS

Swift-Sodium Swift-Sodium provides a safe and easy to use interface to perform common cryptographic operations on macOS, iOS, tvOS and watchOS. It lev

Frank Denis 483 Jan 5, 2023
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
A simple wrapper for the iOS Keychain to allow you to use it in a similar fashion to User Defaults. Written in Swift.

SwiftKeychainWrapper A simple wrapper for the iOS / tvOS Keychain to allow you to use it in a similar fashion to User Defaults. Written in Swift. Prov

Jason 1.5k Dec 30, 2022