You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中使用Cognito Amplify获取ConfirmDevice API的设备密钥

在Flutter Amplify中获取Cognito设备密钥以调用confirmDevice API

前提条件

确保你的Cognito用户池已启用设备追踪:在用户池控制台的「设备追踪」设置中,勾选「记住设备」或「需要确认设备」选项,否则Cognito不会生成设备密钥。

获取设备密钥的方法

Amplify Flutter的Auth模块不会将设备密钥直接暴露在SignInDetails或CognitoAuthSession中,但可以通过专门的设备管理API获取:

  • 使用fetchDevices()方法获取当前已认证用户的设备列表,每个设备对象包含deviceKey字段:
    try {
      final List<AuthDevice> devices = await Amplify.Auth.fetchDevices();
      if (devices.isNotEmpty) {
        String targetDeviceKey = devices.first.deviceKey;
        // 此处可将deviceKey用于后续confirmDevice调用
        print('获取到设备密钥: $targetDeviceKey');
      }
    } on AuthException catch (e) {
      print('获取设备列表失败: ${e.message}');
    }
    

调用confirmDevice的完整示例

拿到设备密钥后,即可调用确认设备的API:

Future<void> confirmUserDevice() async {
  try {
    final devices = await Amplify.Auth.fetchDevices();
    if (devices.isEmpty) {
      print('当前无待确认设备');
      return;
    }

    // 根据用户池设置,如果开启了验证码验证,需传入用户收到的验证码
    await Amplify.Auth.confirmDevice(
      deviceKey: devices.first.deviceKey,
      confirmationCode: 'USER_VERIFICATION_CODE', // 可选,按需添加
    );
    print('设备确认成功');
  } on AuthException catch (e) {
    print('设备确认失败: ${e.message}');
  }
}

注意事项

  1. 必须在用户已认证状态下调用fetchDevices(),未登录用户无法获取设备信息。
  2. 如果用户是首次登录该设备,Cognito会自动生成设备密钥并存储在本地,调用fetchDevices()即可获取。
  3. 若始终无法获取设备密钥,检查用户池设备追踪配置是否正确,以及设备是否已被标记为「已确认」(已确认设备仍可通过fetchDevices()获取密钥)。

内容的提问来源于stack exchange,提问作者Esteban Muñoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:02:19