Flutter local_auth 安全指纹解锁

发布时间:2022-11-30浏览次数:0

支持注册ChatGPT Plus的OneKey虚拟卡
绑定Apple Pay、Google Pay、支付宝和微信支付进行日常消费

注册和了解更多 ->

silver

local_auth

此Flutter插件提供了对用户执行本地设备上身份验证的方法。

这意味着要参考IOS (Touch ID或lock code)上的生物识别认证,以及Android(在Android 6.0中引入)上的指纹api。

Dart中的用法

1 . 添加到库

将其添加到项目的pubspec.yaml文件中:

dependencies:
  local_auth: ^0.3.0

2 .安装

在项目中打开控制台,执行:

flutter packages get

3 .导入

在Dart代码中,使用:

import 'package:local_auth/local_auth.dart';

4 .集成

ios集成

请注意,此插件适用于TouchID和FaceID。但是,要使用后者,还需要添加:

<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>

到Info.plist文件。如果不这样做,会出现一个对话框,告诉用户您的应用尚未更新为使用TouchID。

Android集成

修改项目的AndroidManifest.xml文件以包含 USE_FINGERPRINT权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">
  <uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<manifest>

具体用法

要检查此设备上是否有可用的本地身份验证,请调用canCheckBiometrics

bool canCheckBiometrics = await localAuth.canCheckBiometrics;

目前已实现以下生物识别类型:

  • BiometricType.face (人脸识别)
  • BiometricType.fingerprint (指纹识别)
    要获取已登记的生物识别列表,请调用getAvailableBiometrics:
List<BiometricType> availableBiometrics;
    await auth.getAvailableBiometrics();

if (Platform.isIOS) {
    if (availableBiometrics.contains(BiometricType.face)) {
        // Face ID.
    } else if (availableBiometrics.contains(BiometricType.fingerprint)) {
        // Touch ID.
    }
}

默认对话框,其中包含“确定”按钮,可显示以下两种情况的身份验证错误消息:

  1. 密码/ PIN /模式未设置。用户尚未在iOS上配置密码或在Android上配置PIN /模式。
  2. Touch ID /指纹未注册。用户尚未在设备上注册任何指纹。

也就是说,如果用户的设备上没有指纹,就会弹出一个带有指令的对话框,让用户设置指纹。如果用户点击“确定”按钮,则返回“false”。

使用导出的API通过默认对话框触发本地身份验证:

var localAuth = LocalAuthentication();
bool didAuthenticate =
    await localAuth.authenticateWithBiometrics(
        localizedReason: '请进行身份验证以显示帐户余额');

如果您不想使用默认对话框,请使用’ useerrordialog = false’调用此API。在这种情况下,它会返回错误消息,您需要在省道代码中处理它们:

bool didAuthenticate =
    await localAuth.authenticateWithBiometrics(
        localizedReason: '请进行身份验证以显示帐户余额',
        useErrorDialogs: false);

可以使用默认对话框消息,也可以通过传入IOSAuthMessages和AndroidAuthMessages来使用自己的消息:

import 'package:local_auth/auth_strings.dart';

const andStrings = const AndroidAuthMessages(
	cancelButton: '取消',
	goToSettingsButton: '去设置',
	fingerprintNotRecognized: '指纹识别失败',
	goToSettingsDescription: '请设置指纹.',
	fingerprintHint: '指纹',
	fingerprintSuccess: '指纹识别成功',
	signInTitle: '指纹验证',
	fingerprintRequiredTitle: '请先录入指纹!',
);
authenticated = await auth.authenticateWithBiometrics(
	localizedReason: '扫描指纹进行身份验证',
	useErrorDialogs: false,
	androidAuthStrings :andStrings,
	/* iOSAuthStrings: iosStrings, */
	stickyAuth: true
);

异常

异常有4种类型:PasscodeNotSet、notenroll、NotAvailable和OtherOperatingSystem。它们被包装在LocalAuthenticationError类中。您可以捕获异常并按不同类型处理它们。例如:

import 'package:flutter/services.dart';
import 'package:local_auth/error_codes.dart' as auth_error;

try {
  bool didAuthenticate = await local_auth.authenticateWithBiometrics(
      localizedReason: '请进行身份验证以显示帐户余额');
} on PlatformException catch (e) {
  if (e.code == auth_error.notAvailable) {
    // 在这里处理这个异常。
  }
}

Sticky Auth

您可以将插件上的stickyAuth选项设置为true,以便当系统将应用程序放到后台时插件不会返回失败。如果用户在进行身份验证之前接到电话,就可能发生这种情况。如果stickyAuth设置为false,将导致插件返回失败结果给Dart应用程序。如果设置为true,插件将在应用程序恢复时重试身份验证。

案例

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  /// 本地认证框架
  final LocalAuthentication auth = LocalAuthentication();
  /// 是否有可用的生物识别技术
  bool _canCheckBiometrics;
  /// 生物识别技术列表
  List<BiometricType> _availableBiometrics;
  /// 识别结果
  String _authorized = '验证失败';

  /// 检查是否有可用的生物识别技术
  Future<Null> _checkBiometrics() async {
    bool canCheckBiometrics;
    try {
      canCheckBiometrics = await auth.canCheckBiometrics;
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _canCheckBiometrics = canCheckBiometrics;
    });
  }
  /// 获取生物识别技术列表
  Future<Null> _getAvailableBiometrics() async {
    List<BiometricType> availableBiometrics;
    try {
      availableBiometrics = await auth.getAvailableBiometrics();
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _availableBiometrics = availableBiometrics;
    });
  }
   /// 生物识别
  Future<Null> _authenticate() async {
    bool authenticated = false;
    try {
      authenticated = await auth.authenticateWithBiometrics(
          localizedReason: '扫描指纹进行身份验证',
          useErrorDialogs: true,
          stickyAuth: false);
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _authorized = authenticated ? '验证通过' : '验证失败';
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('插件的示例应用程序'),
      ),
      body: ConstrainedBox(
          constraints: const BoxConstraints.expand(),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                Text('是否有可用的生物识别技术: $_canCheckBiometrics\n'),
                RaisedButton(
                  child: const Text('检查生物识别技术'),
                  onPressed: _checkBiometrics,
                ),
                Text('可用的生物识别技术: $_availableBiometrics\n'),
                RaisedButton(
                  child: const Text('获取可用的生物识别技术'),
                  onPressed: _getAvailableBiometrics,
                ),
                Text('状态: $_authorized\n'),
                RaisedButton(
                  child: const Text('验证'),
                  onPressed: _authenticate,
                )
              ])),
    ));
  }
}
字节笔记本扫描二维码查看更多内容