Coder Social home page Coder Social logo

rushisangani / biometricauthentication Goto Github PK

View Code? Open in Web Editor NEW
828.0 19.0 110.0 322 KB

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

License: MIT License

Swift 93.13% Objective-C 2.35% Ruby 4.52%
authentication faceid touchid biometric-identification biometric apple fingerprint-authentication facerecognition fingerprint face

biometricauthentication's Introduction

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.

biometricauthentication's People

Contributors

basvankuijck avatar dimitryvin avatar evertoncunha avatar irshadpc avatar rushisangani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

biometricauthentication's Issues

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

What About Older devices

Hi Rushi,
Thanks for the lib.
I don't have the device which is not supported touchId like (iPhone 4s, iPhone 5).
Is this case handle in this library ?

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

What does the project add to LocalAuthentication framework API?

May I ask what are the project's additional features compared to the built-in LocalAuthentication framework? I read the usage section in readme and tried the example, but it's still not clear to me. BTW, when trying the example, I notice that the project doesn't support device passcode by default (I believe it can be customized because there is a section in readme discussing fallback title). In my opinion, that's more like a limitation because if user doesn't enable touch/face id, it's better off to just use passcode rather than ask user to enable touch/face if for the app.

Background: I'm adding user authentication support to my app. I read LocalAuthentication doc and find it's simple to use. During the course I also find this project, which I believe is a wrapper of LocalAuthentication. But it's not clear to me what are the additional features the project provide. I think it may help to list them in readme for people to evaluate the project. Just my thought. Thanks.

SPM Support

Hello,

Please add Swift Package Manager installation

Thanks,

Demo cannot run with new key

"This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSFaceIDUsageDescription key with a string value explaining to the user how the app uses this data."

The Demo app's info.plist just needs this key.

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 ?

Any chance you can help change the BioAuthenticator.swift so it can be used by existing Objective C project?

It seems that Objective C is having trouble importing the public methods (if I add the @objc attribute to it). The success function block and failure function block is not compatible with Objective C.

thanks,

BioMetricAuthenticator.swift:52:203: Function types cannot be represented in Objective-C unless their parameters and returns can be

    /// Check for biometric authentication
    public class func authenticateWithBioMetrics(reason: String, fallbackTitle: String? = "", cancelTitle: String? = "", success successBlock:@escaping AuthenticationSuccess, failure failureBlock:@escaping AuthenticationFailure)

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

Apple's update to their API policy - Required Reason in Privacy manifest

Describe the feature or problem you’d like to solve

From Fall 2023 Apple starts rolling out new privacy requirements, The apps and third-party SDKs should contain a privacy manifest file when they access required reason API. SkeletonView SDK uses UserDefaults which is required description of use in PrivacyManifest.
Otherwise, apps that don’t describe their use of required reason API in their privacy manifest file won’t be accepted by App Store Connect. Here is a link to the [Apple documentation].(https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api).

Proposed solution

Add a PrivacyInfo.xcprivacy file and the following information to the Privacy Accessed API Types section
Privacy Accessed API Type: User Defaults
Privacy Accessed API Reasons: CA92.1: Access info from same app, per documentation

Additional context

Apple documentation

Do you support Swift 4?

Got the following error message:

/Authentication/BioMetricAuthenticator.swift:70:138: Use of undeclared type 'Result'

Do you have code for Swift 4?

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.

App rejected!

Thanks for great library but Apple rejected our app because of this :( Here is the message from Apple :

our app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change.

Specifically, your app uses the following non-public URL scheme:

app-prefs:root=touchid_passcode

Continuing to use or conceal non-public APIs in future submissions of this app may result in the termination of your Apple Developer account, as well as removal of all associated apps from the App Store.

Next Steps

To resolve this issue, please revise your app to provide the associated functionality using public APIs or remove the functionality using the "prefs:root" or "App-Prefs:root" URL scheme.

If there are no alternatives for providing the functionality your app requires, you can file an enhancement request.

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]

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?

Authenticate view appears on other screens such as notification

I set a timer of 5 min to logout the app and shows loginViewConroller. In view will appear I call the Authenticate method.

But the problem is if the user is not on app screen and reading notification. When timer triggers and authenticate view appears on top of Notification screen.

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

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

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

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
}

Cannot import BiometricAuthentication

I use latest version of BiometricAuthentication (2.2), after pod install.
When I try to import BiometricAuthentication, it cannot show snippet.
When I add manually import BiometricAuthentication, it has crash on modulemap and some private func.

Please repair this.
I use Xcode 10.1 and swift 4.2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.