Bio-metric Authentications in Flutter

0

 



The authentications that matter on bodily traits are acknowledged as bio-metric authentications — such as Fingerprint/Touch ID or Face ID. Most cutting-edge cellular functions are presenting bio-metric authentications to their customers for the sake of speedy access. It’s very frequent in banking functions or functions that have login classes that place customers have to authenticate themselves on each new session.


Flutter additionally helps biometric authentication with the assist of a plugin named local_auth authored by using flutter.dev itself. Let’s dive into the code and see how we can put in force it in a few easy steps. 


1. Add local_auth dependency to your pubspec.yaml file:


dependencies:

  local_auth: ^2.1.0


2. Navigate to your MainActivity file, either it’s in your Java or Kotlin folder.


android > app > src > main > kotlin or java > MainActivity

Replace FlutterActivity with FlutterFragmentActivity and your final file should look like this:


If Kotlin:


package com.example.biometric_auth


import io.flutter.embedding.android.FlutterFragmentActivity


class MainActivity: FlutterFragmentActivity() {

    // ...

}


If Java:


package com.example.yourpackagename;

  

import io.flutter.embedding.android.FlutterFragmentActivity;


public class MainActivity extends FlutterFragmentActivity {

      // ...

}


3. In your android > app > src > main > AndroidManifest.xml file, add the following line to use fingerprint permissions.



<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.biometric_auth">

    

    <!--Add this line !-->

    <uses-permission android:name="android.permission.USE_FINGERPRINT"/>

   

    <application

        .....

        

That’s it for Android Configurations, you simply want to add a key in Info.plist file to configure it for iOS. 


4. Add the following key in Info.plist file, with your reason explaining why you need to authenticate users with Face ID.


<key>NSFaceIDUsageDescription</key>

<string>Write reason here, Why your app authenticates using face id?</string>


We are done with configurations, it’s time for some real action now!




I created this easy UI for demonstration, let’s say we have a button that lets in customers to authenticate the usage of bio-metric, however right here comes a check case —


Not each gadget helps bio-metric — some have fingerprints, some have face IDs and some have neither of them. Even if they do, it’s no longer imperative that the consumer has enrolled them from their smartphone settings. To address this, we have a helper characteristic getAvailableBiometrics from the local_auth plugin that returns the listing of enrolled bio-metrics of a specific device. If the back listing is empty, it ability the person has no longer enrolled in any bio-metrics.


5. I created a feature named hasEnrolledBiometrics() which helps me figure out if I desire to exhibit the Bio-metric login button to a person or not. It returns a bool, proper if the consumer has biometrics enabled, and false for the opposite. 



import 'package:local_auth/local_auth.dart';


class BiometricHelper {

  final LocalAuthentication _auth = LocalAuthentication();


  Future<bool> hasEnrolledBiometrics() async {

    final List<BiometricType> availableBiometrics =

        await _auth.getAvailableBiometrics();


    if (availableBiometrics.isNotEmpty) {

      return true;

    }

    return false;

  }

}


6. Hence, my button ought to be solely displayed if the person has some enrolled biometrics on his device.


bool showBiometric = false;

  @override

  void initState() {

    isBiometricsAvailable();

    super.initState();

  }


  isBiometricsAvailable() async {

    showBiometric = await BiometricHelper().hasEnrolledBiometrics();

    setState(() {});

  }


  @override

  Widget build(BuildContext context) {

    return Scaffold(

      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,

          children: [

            if (showBiometric)

              MaterialButton(

                color: Colors.blue,

                child: const Text(

                  'Biometric Login',

                  style: TextStyle(

                    color: Colors.white,

                  ),

                ),

                onPressed: () {},

              ),

          ],

        ),

      ),

    );

  }


7. Time to enforce onPressed performance on the button. For that purpose, we will use authenticate helper feature from local_auth plugin. 


import 'package:local_auth/local_auth.dart';


class BiometricHelper {

  final LocalAuthentication _auth = LocalAuthentication();


  Future<bool> authenticate() async {

    final bool didAuthenticate = await _auth.authenticate(

        localizedReason: 'Please authenticate to proceed',

        options: const AuthenticationOptions(biometricOnly: true));

    return didAuthenticate;

  }

  

}


This function now returns true if the authentication is successful or false otherwise


Final Code:

Our updated widget tree looks like this:


@override

  Widget build(BuildContext context) {

    return Scaffold(

      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,

          children: [

            if (showBiometric)

              MaterialButton(

                color: Colors.blue,

                child: const Text(

                  'Biometric Login',

                  style: TextStyle(

                    color: Colors.white,

                  ),

                ),

                onPressed: () async {

                  isAuthenticated = await BiometricHelper().authenticate();

                  setState(() {});

                },

              ),

            if (isAuthenticated)

              const Padding(

                padding: EdgeInsets.only(top: 20.0),

                child: Text(

                  'Secret Information\nonly for authenticated users',

                  textAlign: TextAlign.center,

                  style: TextStyle(color: Colors.green, fontSize: 18),

                ),

              ),

          ],

        ),

      ),

    );

  }


Our updated bio-metric helper class looks like this:


import 'package:local_auth/local_auth.dart';


class BiometricHelper {

  final LocalAuthentication _auth = LocalAuthentication();


  Future<bool> hasEnrolledBiometrics() async {

    final List<BiometricType> availableBiometrics =

        await _auth.getAvailableBiometrics();


    if (availableBiometrics.isNotEmpty) {

      return true;

    }

    return false;

  }


  Future<bool> authenticate() async {

    final bool didAuthenticate = await _auth.authenticate(

        localizedReason: 'Please authenticate to proceed',

        options: const AuthenticationOptions(biometricOnly: true));

    return didAuthenticate;

  }

}


This way, as soon as authentication is successful, solely then the consumer will be proven the textual content widget of secret information

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !