Flutter本地身份验证插件local_auth_credentials的使用

Flutter本地身份验证插件local_auth的使用

该Flutter插件提供了在设备上进行本地用户认证的方法。

在支持的设备上,这包括生物识别认证(如指纹或面部识别)。

Android iOS Windows
支持 SDK 16+* 9.0+ Windows 10+

使用

设备功能检查

要检查设备是否支持本地认证,可以调用canCheckBiometrics(如果需要生物识别支持)和/或isDeviceSupported()(如果只需要一些设备级别的认证):

import 'package:local_auth/local_auth.dart';

final LocalAuthentication auth = LocalAuthentication();
final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics;
final bool canAuthenticate =
    canAuthenticateWithBiometrics || await auth.isDeviceSupported();

目前实现的生物识别类型包括:

  • BiometricType.face
  • BiometricType.fingerprint
  • BiometricType.weak
  • BiometricType.strong

已注册的生物识别

canCheckBiometrics仅表示硬件支持,而不是设备是否有任何生物识别已注册。要获取已注册的生物识别列表,请调用getAvailableBiometrics()

类型是设备特定和平台特定的,并且将来可能会添加其他类型,因此可能时不应依赖特定的生物识别类型,而应检查是否有任何生物识别已注册:

final List<BiometricType> availableBiometrics =
    await auth.getAvailableBiometrics();

if (availableBiometrics.isNotEmpty) {
  // 有生物识别已注册。
}

if (availableBiometrics.contains(BiometricType.strong) ||
    availableBiometrics.contains(BiometricType.face)) {
  // 特定类型的生物识别可用。
  // 小心使用此类检查!
}

选项

authenticate()方法在可能的情况下使用生物识别认证,但也允许回退到PIN、图案或密码。

try {
  final bool didAuthenticate = await auth.authenticate(
      localizedReason: '请进行身份验证以查看账户余额');
  // ···
} on PlatformException {
  // ...
}

要要求生物识别认证,传递带有biometricOnly设置为trueAuthenticationOptions

final bool didAuthenticate = await auth.authenticate(
    localizedReason: '请进行身份验证以查看账户余额',
    options: const AuthenticationOptions(biometricOnly: true));

注意biometricOnly不支持Windows,因为Windows实现的底层API(Windows Hello)不支持选择认证方法。

对话框

插件为以下情况提供了默认对话框:

  1. 密码/PIN/图案未设置:用户尚未在iOS上配置密码或在Android上配置PIN/图案。
  2. 生物识别未注册:用户尚未在设备上注册任何生物识别。

如果用户在调用authenticate时没有必要的认证,则会给出注册的选项,或者取消认证。

如果您不想使用默认对话框,可以将useErrorDialogs选项设置为false,以便authenticate立即返回错误。

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

try {
  final bool didAuthenticate = await auth.authenticate(
      localizedReason: '请进行身份验证以查看账户余额',
      options: const AuthenticationOptions(useErrorDialogs: false));
  // ···
} on PlatformException catch (e) {
  if (e.code == auth_error.notAvailable) {
    // 处理没有硬件的情况。
  } else if (e.code == auth_error.notEnrolled) {
    // 处理没有生物识别的情况。
  } else {
    // 处理其他错误。
  }
}

如果您想自定义对话框中的消息,可以传递AuthMessages用于每个您支持的平台。这些是平台特定的,因此您需要导入平台特定的实现包。例如,要自定义Android和iOS:

import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';

final bool didAuthenticate = await auth.authenticate(
    localizedReason: '请进行身份验证以查看账户余额',
    authMessages: const [
      AndroidAuthMessages(
        signInTitle: 'Oops! 需要生物识别认证!',
        cancelButton: '不,谢谢',
      ),
      IOSAuthMessages(
        cancelButton: '不,谢谢',
      ),
    ]);

如果您想处理authenticate抛出的PlatformException,请参阅error_codes.dart了解可能需要特定处理的已知错误代码。

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

final LocalAuthentication auth = LocalAuthentication();

try {
  final bool didAuthenticate = await auth.authenticate(
      localizedReason: '请进行身份验证以查看账户余额',
      options: const AuthenticationOptions(useErrorDialogs: false));
  // ···
} on PlatformException catch (e) {
  if (e.code == auth_error.notEnrolled) {
    // 处理没有生物识别的情况。
  } else if (e.code == auth_error.lockedOut || e.code == auth_error.permanentlyLockedOut) {
    // 处理锁定的情况。
  } else {
    // 处理其他错误。
  }
}

iOS集成

请注意,该插件支持Touch ID和Face ID。但是,要使用后者,您还需要在Info.plist文件中添加:

<key>NSFaceIDUsageDescription</key>
<string>为什么我的应用要使用面部识别进行身份验证?</string>

如果不这样做,将会出现一个对话框,告诉用户您的应用尚未更新为使用Face ID。

Android集成

  • 插件将在SDK 16+上构建和运行,但在SDK 23(Android 6.0)之前isDeviceSupported()始终返回false。

活动更改

请注意,local_auth需要使用FragmentActivity而不是Activity。要更新您的应用程序:

  • 如果您直接使用FlutterActivity,请将其更改为AndroidManifest.xml中的FlutterFragmentActivity

  • 如果您使用的是自定义活动,请更新您的MainActivity.java

import io.flutter.embedding.android.FlutterFragmentActivity;

public class MainActivity extends FlutterFragmentActivity {
    // ...
}

或MainActivity.kt:

import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {
    // ...
}

使其继承自FlutterFragmentActivity

权限

更新您的项目AndroidManifest.xml文件以包含USE_BIOMETRIC权限:

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

更多关于Flutter本地身份验证插件local_auth_credentials的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地身份验证插件local_auth_credentials的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


local_auth 是 Flutter 中用于本地身份验证的插件,支持指纹、面部识别、PIN 码等生物识别认证方式。要使用 local_auth,你需要先将其添加到项目中,并按照以下步骤进行配置和使用。

1. 添加依赖

pubspec.yaml 文件中添加 local_auth 依赖:

dependencies:
  flutter:
    sdk: flutter
  local_auth: ^2.1.0

然后运行 flutter pub get 来安装依赖。

2. 配置平台

Android

android/app/src/main/AndroidManifest.xml 文件中添加以下权限:

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

iOS

ios/Runner/Info.plist 文件中添加以下键值对:

<key>NSFaceIDUsageDescription</key>
<string>We need to use Face ID to authenticate you.</string>

3. 使用 local_auth

在你的 Dart 文件中导入 local_auth 插件:

import 'package:local_auth/local_auth.dart';

初始化 LocalAuthentication

final LocalAuthentication auth = LocalAuthentication();

检查设备是否支持生物识别

bool canCheckBiometrics = await auth.canCheckBiometrics;
List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();

if (!canCheckBiometrics || availableBiometrics.isEmpty) {
  // 设备不支持生物识别
  print("Biometrics not available");
} else {
  // 设备支持生物识别
  print("Available biometrics: $availableBiometrics");
}

进行身份验证

try {
  bool authenticated = await auth.authenticate(
    localizedReason: 'Please authenticate to continue',
    options: const AuthenticationOptions(
      biometricOnly: true, // 仅使用生物识别(不显示备用选项)
    ),
  );

  if (authenticated) {
    // 认证成功
    print("Authenticated");
  } else {
    // 认证失败
    print("Not Authenticated");
  }
} catch (e) {
  // 处理异常
  print("Error: $e");
}

4. 处理不同的生物识别类型

你可以根据设备支持的生物识别类型(如指纹、面部识别)来调整 UI 或逻辑:

List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics();

if (availableBiometrics.contains(BiometricType.face)) {
  // 设备支持面部识别
  print("Face ID is available");
} else if (availableBiometrics.contains(BiometricType.fingerprint)) {
  // 设备支持指纹识别
  print("Fingerprint is available");
}

5. 处理错误和异常

authenticate 方法可能会抛出多种异常,例如用户取消认证、设备不支持生物识别等。你可以使用 try-catch 来捕获并处理这些异常。

try {
  bool authenticated = await auth.authenticate(
    localizedReason: 'Please authenticate to continue',
  );

  if (authenticated) {
    print("Authenticated");
  } else {
    print("Not Authenticated");
  }
} on PlatformException catch (e) {
  print("PlatformException: ${e.message}");
} catch (e) {
  print("Error: $e");
}

6. 其他配置

local_auth 还提供了其他选项,例如设置 useErrorDialogs 来显示系统默认的错误对话框,或者设置 stickyAuth 来保持认证状态。

bool authenticated = await auth.authenticate(
  localizedReason: 'Please authenticate to continue',
  options: const AuthenticationOptions(
    useErrorDialogs: true, // 显示系统默认的错误对话框
    stickyAuth: true, // 保持认证状态
  ),
);

7. 处理认证失败后的备用方案

如果用户无法使用生物识别,你可以提供一个备用方案,例如使用 PIN 码或密码。

bool authenticated = await auth.authenticate(
  localizedReason: 'Please authenticate to continue',
  options: const AuthenticationOptions(
    biometricOnly: false, // 允许使用PIN码或密码作为备用方案
  ),
);

8. 处理认证结果

根据认证结果,你可以执行不同的逻辑:

if (authenticated) {
  // 认证成功,执行相关操作
  print("Authenticated");
} else {
  // 认证失败,提示用户
  print("Not Authenticated");
}
回到顶部