local_auth
此Flutter插件提供了對(duì)用戶執(zhí)行本地設(shè)備上身份驗(yàn)證的方法
這意味著要參考IOS (Touch ID或lock code)上的生物識(shí)別認(rèn)證撤卢,以及Android(在Android 6.0中引入)上的指紋api督赤。
Dart中的用法
1 . 添加到庫
將其添加到項(xiàng)目的pubspec.yaml文件中:
此版本比較穩(wěn)定 沒有出現(xiàn)過問題
dependencies:
local_auth: ^0.6.1+3
2 .安裝
在項(xiàng)目中打開控制臺(tái),執(zhí)行:
flutter packages get
3 .導(dǎo)入
在Dart代碼中,使用:
import 'package:local_auth/local_auth.dart';
4 .集成
iOS集成
請(qǐng)注意,此插件適用于TouchID和FaceID试幽。但是,要使用后者锄列,還需要添加:
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
到Info.plist文件。如果不這樣做惯悠,會(huì)出現(xiàn)一個(gè)對(duì)話框邻邮,告訴用戶您的應(yīng)用尚未更新為使用TouchID。
Android集成
修改項(xiàng)目的AndroidManifest.xml文件以包含 USE_FINGERPRINT權(quán)限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<manifest>
具體用法
要檢查此設(shè)備上是否有可用的本地身份驗(yàn)證克婶,請(qǐng)調(diào)用canCheckBiometrics:
bool canCheckBiometrics = await localAuth.canCheckBiometrics;
目前已實(shí)現(xiàn)以下生物識(shí)別類型:
- BiometricType.face (人臉識(shí)別)
- BiometricType.fingerprint (指紋識(shí)別)
要獲取已登記的生物識(shí)別列表饶囚,請(qǐng)調(diào)用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.
}
}
默認(rèn)對(duì)話框,其中包含“確定”按鈕鸠补,可顯示以下兩種情況的身份驗(yàn)證錯(cuò)誤消息:
- 密碼/ PIN /模式未設(shè)置萝风。用戶尚未在iOS上配置密碼或在Android上配置PIN /模式。
- Touch ID /指紋未注冊(cè)紫岩。用戶尚未在設(shè)備上注冊(cè)任何指紋规惰。
也就是說,如果用戶的設(shè)備上沒有指紋泉蝌,就會(huì)彈出一個(gè)帶有指令的對(duì)話框歇万,讓用戶設(shè)置指紋。如果用戶點(diǎn)擊“確定”按鈕勋陪,則返回“false”贪磺。
使用導(dǎo)出的API通過默認(rèn)對(duì)話框觸發(fā)本地身份驗(yàn)證:
var localAuth = LocalAuthentication();
bool didAuthenticate =
await localAuth.authenticateWithBiometrics(
localizedReason: '請(qǐng)進(jìn)行身份驗(yàn)證以顯示帳戶余額');
如果您不想使用默認(rèn)對(duì)話框,請(qǐng)使用’ useerrordialog = false’調(diào)用此API诅愚。在這種情況下寒锚,它會(huì)返回錯(cuò)誤消息,您需要在省道代碼中處理它們:
bool didAuthenticate =
await localAuth.authenticateWithBiometrics(
localizedReason: '請(qǐng)進(jìn)行身份驗(yàn)證以顯示帳戶余額',
useErrorDialogs: false);
可以使用默認(rèn)對(duì)話框消息违孝,也可以通過傳入IOSAuthMessages和AndroidAuthMessages來使用自己的消息:
import 'package:local_auth/auth_strings.dart';
const andStrings = const AndroidAuthMessages(
cancelButton: '取消',
goToSettingsButton: '去設(shè)置',
fingerprintNotRecognized: '指紋識(shí)別失敗',
goToSettingsDescription: '請(qǐng)?jiān)O(shè)置指紋.',
fingerprintHint: '指紋',
fingerprintSuccess: '指紋識(shí)別成功',
signInTitle: '指紋驗(yàn)證',
fingerprintRequiredTitle: '請(qǐng)先錄入指紋!',
);
authenticated = await auth.authenticateWithBiometrics(
localizedReason: '掃描指紋進(jìn)行身份驗(yàn)證',
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: '請(qǐng)進(jìn)行身份驗(yàn)證以顯示帳戶余額');
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
// 在這里處理這個(gè)異常校坑。
}
}
Sticky Auth
您可以將插件上的stickyAuth選項(xiàng)設(shè)置為true拣技,以便當(dāng)系統(tǒng)將應(yīng)用程序放到后臺(tái)時(shí)插件不會(huì)返回失敗千诬。如果用戶在進(jìn)行身份驗(yàn)證之前接到電話,就可能發(fā)生這種情況膏斤。如果stickyAuth設(shè)置為false徐绑,將導(dǎo)致插件返回失敗結(jié)果給Dart應(yīng)用程序。如果設(shè)置為true掸绞,插件將在應(yīng)用程序恢復(fù)時(shí)重試身份驗(yàn)證。
案例
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> {
/// 本地認(rèn)證框架
final LocalAuthentication auth = LocalAuthentication();
/// 是否有可用的生物識(shí)別技術(shù)
bool _canCheckBiometrics;
/// 生物識(shí)別技術(shù)列表
List<BiometricType> _availableBiometrics;
/// 識(shí)別結(jié)果
String _authorized = '驗(yàn)證失敗';
/// 檢查是否有可用的生物識(shí)別技術(shù)
Future<Null> _checkBiometrics() async {
bool canCheckBiometrics;
try {
canCheckBiometrics = await auth.canCheckBiometrics;
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_canCheckBiometrics = canCheckBiometrics;
});
}
/// 獲取生物識(shí)別技術(shù)列表
Future<Null> _getAvailableBiometrics() async {
List<BiometricType> availableBiometrics;
try {
availableBiometrics = await auth.getAvailableBiometrics();
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_availableBiometrics = availableBiometrics;
});
}
/// 生物識(shí)別
Future<Null> _authenticate() async {
bool authenticated = false;
try {
authenticated = await auth.authenticateWithBiometrics(
localizedReason: '掃描指紋進(jìn)行身份驗(yàn)證',
useErrorDialogs: true,
stickyAuth: false);
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
setState(() {
_authorized = authenticated ? '驗(yàn)證通過' : '驗(yàn)證失敗';
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件的示例應(yīng)用程序'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text('是否有可用的生物識(shí)別技術(shù): $_canCheckBiometrics\n'),
RaisedButton(
child: const Text('檢查生物識(shí)別技術(shù)'),
onPressed: _checkBiometrics,
),
Text('可用的生物識(shí)別技術(shù): $_availableBiometrics\n'),
RaisedButton(
child: const Text('獲取可用的生物識(shí)別技術(shù)'),
onPressed: _getAvailableBiometrics,
),
Text('狀態(tài): $_authorized\n'),
RaisedButton(
child: const Text('驗(yàn)證'),
onPressed: _authenticate,
)
])),
));
}
}