Flutter原生认证插件native_authentication的使用

Flutter原生认证插件native_authentication的使用

简介

native_authentication 是一个用 Dart 编写的库,用于通过原生 API 执行身份验证流程。以下是 NativeAuthentication 的平台实现:

平台 实现
iOS/macOS ASWebAuthenticationSession
Android Custom Tabs
Linux/Windows 本地 HTTP 服务器
Web HTTP 重定向

示例代码

以下是一个完整的示例代码,展示如何在 Flutter 中使用 native_authentication 插件。

示例代码

import 'dart:developer';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:native_authentication/native_authentication.dart';

// 创建 NativeAuthentication 实例
final NativeAuthentication nativeAuth = NativeAuthentication(
  logger: Logger.root,
);

void main() {
  // 设置日志级别为 ALL
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((record) {
    log(
      record.message,
      level: record.level.value,
      name: record.loggerName,
    );
  });
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  // 保存回调结果
  Future<String> _result = Future<String>.value('awaiting callback');

  // 根据平台选择合适的回调类型
  CallbackType get callbackType {
    const localhost = CallbackType.localhost(port: 7777);
    if (kIsWeb) {
      return localhost;
    }
    return switch (Platform.operatingSystem) {
      'ios' || 'android' || 'macos' => const CallbackType.custom('celest'),
      _ => localhost,
    };
  }

  // 执行回调操作
  Future<void> _performCallback() async {
    // 启动回调会话
    final session = nativeAuth.startCallback(
      uri: Uri.parse('https://my-authorization-server'), // 授权服务器 URI
      type: callbackType, // 回调类型
    );
    // 更新 UI 显示回调结果
    setState(() {
      _result = session.redirectUri.then((uri) => 'callback: $uri');
    });
  }

  @override
  Widget build(BuildContext context) {
    const textStyle = TextStyle(fontSize: 25);
    const spacerSmall = SizedBox(height: 10);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('原生认证示例'),
        ),
        body: Center(
          child: Container(
            padding: const EdgeInsets.all(10),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 按钮触发回调操作
                ElevatedButton(
                  onPressed: _performCallback,
                  child: const Text('执行回调'),
                ),
                spacerSmall,
                // 显示回调结果
                FutureBuilder<String>(
                  future: _result,
                  builder: (BuildContext context, AsyncSnapshot<String> value) {
                    final displayValue = (value.hasData)
                        ? value.data
                        : value.hasError
                            ? '${value.error}'
                            : '加载中...';
                    return Text(
                      '结果 = $displayValue',
                      style: textStyle,
                      textAlign: TextAlign.center,
                    );
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

代码说明

  1. 导入必要的包

    • flutter/foundationflutter/material 提供基础的 Flutter 功能。
    • logging 用于记录日志。
    • native_authentication 是核心插件。
  2. 创建 NativeAuthentication 实例

    final NativeAuthentication nativeAuth = NativeAuthentication(
      logger: Logger.root,
    );
    
  3. 设置日志级别

    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((record) {
      log(
        record.message,
        level: record.level.value,
        name: record.loggerName,
      );
    });
    
  4. 定义回调类型

    • 根据平台选择合适的回调类型(如 localhostcustom)。
    CallbackType get callbackType {
      const localhost = CallbackType.localhost(port: 7777);
      if (kIsWeb) {
        return localhost;
      }
      return switch (Platform.operatingSystem) {
        'ios' || 'android' || 'macos' => const CallbackType.custom('celest'),
        _ => localhost,
      };
    }
    
  5. 执行回调操作

    • 使用 startCallback 方法启动回调会话。
    Future<void> _performCallback() async {
      final session = nativeAuth.startCallback(
        uri: Uri.parse('https://my-authorization-server'),
        type: callbackType,
      );
      setState(() {
        _result = session.redirectUri.then((uri) => 'callback: $uri');
      });
    }
    
  6. UI 部分

    • 包含一个按钮触发回调操作,并显示回调结果。
    ElevatedButton(
      onPressed: _performCallback,
      child: const Text('执行回调'),
    ),
    FutureBuilder<String>(
      future: _result,
      builder: (BuildContext context, AsyncSnapshot<String> value) {
        final displayValue = (value.hasData)
            ? value.data
            : value.hasError
                ? '${value.error}'
                : '加载中...';
        return Text(
          '结果 = $displayValue',
          style: textStyle,
          textAlign: TextAlign.center,
        );
      },
    ),
    

更多关于Flutter原生认证插件native_authentication的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生认证插件native_authentication的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


native_authentication 是一个 Flutter 插件,用于在 iOS 和 Android 设备上使用原生认证方法(如指纹、面部识别或 PIN 码)进行用户身份验证。它提供了一种简单的方式来集成设备的安全功能到 Flutter 应用中。

以下是使用 native_authentication 插件的步骤和示例代码:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 native_authentication 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  native_authentication: ^0.0.1 # 请使用最新版本

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

2. 导入插件

在 Dart 文件中导入 native_authentication 插件:

import 'package:native_authentication/native_authentication.dart';

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

在尝试进行身份验证之前,通常需要检查设备是否支持生物识别功能(如指纹或面部识别):

bool isBiometricSupported = await NativeAuthentication.isBiometricSupported();
if (isBiometricSupported) {
  print("设备支持生物识别");
} else {
  print("设备不支持生物识别");
}

4. 进行身份验证

使用 authenticate 方法进行身份验证:

try {
  bool isAuthenticated = await NativeAuthentication.authenticate(
    localizedReason: "请验证您的身份以继续", // 显示给用户的提示信息
    useErrorDialogs: true, // 是否显示错误对话框
    stickyAuth: false, // 是否在后台保持认证状态
  );

  if (isAuthenticated) {
    print("身份验证成功");
  } else {
    print("身份验证失败");
  }
} catch (e) {
  print("身份验证出错: $e");
}

5. 处理错误

在身份验证过程中,可能会遇到各种错误,例如用户取消操作、设备不支持生物识别等。你可以通过捕获异常来处理这些错误:

try {
  bool isAuthenticated = await NativeAuthentication.authenticate(
    localizedReason: "请验证您的身份以继续",
    useErrorDialogs: true,
    stickyAuth: false,
  );

  if (isAuthenticated) {
    print("身份验证成功");
  } else {
    print("身份验证失败");
  }
} on PlatformException catch (e) {
  if (e.code == "auth_canceled") {
    print("用户取消了身份验证");
  } else if (e.code == "auth_failed") {
    print("身份验证失败");
  } else {
    print("身份验证出错: ${e.message}");
  }
} catch (e) {
  print("身份验证出错: $e");
}

6. 其他功能

native_authentication 插件可能还提供了其他功能,例如检查是否已经设置了生物识别认证、获取可用的生物识别类型等。你可以查阅插件的文档或源代码来了解更多信息。

注意事项

  • 权限: 在 Android 上,你可能需要在 AndroidManifest.xml 中添加 USE_FINGERPRINTUSE_BIOMETRIC 权限。
  • iOS 配置: 在 iOS 上,你需要在 Info.plist 文件中添加 NSFaceIDUsageDescription 密钥,以描述应用使用面部识别的原因。

示例代码

以下是一个完整的示例代码,展示如何使用 native_authentication 插件进行身份验证:

import 'package:flutter/material.dart';
import 'package:native_authentication/native_authentication.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Native Authentication Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              bool isBiometricSupported = await NativeAuthentication.isBiometricSupported();
              if (isBiometricSupported) {
                try {
                  bool isAuthenticated = await NativeAuthentication.authenticate(
                    localizedReason: "请验证您的身份以继续",
                    useErrorDialogs: true,
                    stickyAuth: false,
                  );

                  if (isAuthenticated) {
                    print("身份验证成功");
                  } else {
                    print("身份验证失败");
                  }
                } on PlatformException catch (e) {
                  if (e.code == "auth_canceled") {
                    print("用户取消了身份验证");
                  } else if (e.code == "auth_failed") {
                    print("身份验证失败");
                  } else {
                    print("身份验证出错: ${e.message}");
                  }
                } catch (e) {
                  print("身份验证出错: $e");
                }
              } else {
                print("设备不支持生物识别");
              }
            },
            child: Text('Authenticate'),
          ),
        ),
      ),
    );
  }
}
回到顶部