Flutter | GW アドベントカレンダーの5日目の記事です。
顔認証/指紋認証を実装するために、Flutter公式のlocal_authプラグインを使用します。
完成形
以下のような感じで、顔認証/指紋認証を実装します。
顔認証
![face.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F396229%2Fa9a4bac5-81b9-e056-f3b8-0ebcdeb84298.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=148d767659195c791caa2885083c166a)
指紋認証
![touch.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F396229%2F2957ca46-40d9-30a3-d703-a90b2e12c9c1.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=38c482dc2bfe7e748718f6fa4ad84415)
Android
![android_touch.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F396229%2Fce89ff4e-e99a-5a7d-e0bc-92eade1cef03.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=a1d1e4459ef576df30b701eeef36a133)
顔認証/指紋認証の実装
1. プラグインとの紐付け
pubspec.yaml
dependencies:
local_auth: ^0.4.0+1 // 追加
バージョンについては、local_authを参照してください。
2. 生体認証設定
iOSとAndroid側で以下を追加して、生体認証を行えるようにします。
iOS
info.plist
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
Android
AndroidManifest.xml
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
顔認証/指紋認証の実装
main.dart
import 'package:local_auth/local_auth.dart';
端末の可能な生体認証タイプを取得
main.dart
LocalAuthentication _localAuth = LocalAuthentication();
Future<List<BiometricType>> _getAvailableBiometricTypes() async {
List<BiometricType> availableBiometricTypes;
try {
availableBiometricTypes = await _localAuth.getAvailableBiometrics();
} on PlatformException catch (e) {
// TODO
}
return availableBiometricTypes;
}
生体認証を要求
main.dart
Future<bool> _authenticate() async {
bool result = false;
List<BiometricType> availableBiometricTypes = await _getAvailableBiometricTypes();
try {
if (availableBiometricTypes.contains(BiometricType.face)
|| availableBiometricTypes.contains(BiometricType.fingerprint)) {
result = await _localAuth.authenticateWithBiometrics(localizedReason: "認証してください");
}
} on PlatformException catch (e) {
// TODO
}
return result;
}
指紋/顔を登録していない場合の挙動は?
以下のように、登録を促すダイアログを自動的に表示してくれます。
ここで、顔や指紋を登録せずに「OK」ボタンを押された際には、認証結果がfalseで返ってきます。
![touch_setting.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F396229%2F7bc9ca42-0073-3839-c5ff-2335ac87086c.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=5085274a9781f8c67cbe57136f9a3545)
Android
まとめ
local_authプラグインを実装しているだけです。
指紋認証も顔認証もかなり簡単に実装できてしまいます。
念のため、githubにプロジェクトおいています。
Flutterつよし!!!!