You need to enable JavaScript to run this app. 如何在Flutter中借助AWS Cognito实现带OTP的无密码登录?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中借助AWS Cognito实现带OTP的无密码登录?

Flutter基于官方Amplify实现Cognito OTP无密码登录全流程

依赖引入

在项目pubspec.yaml的dependencies配置块添加以下可稳定运行的官方包:

  • amplify_flutter: ^1.7.0
  • amplify_auth_cognito: ^1.7.0
    执行flutter pub get完成依赖拉取。

前置准备

确保你的Cognito用户池已开启OTP登录能力,记录好对应的用户池区域、用户池ID、应用客户端ID参数,用于后续SDK初始化,无需引入其他第三方认证依赖。

核心认证服务封装

创建AuthService单例类,封装Amplify认证全链路逻辑,代码可直接复用:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';

class AuthService {
  AuthService._privateConstructor();
  static final AuthService instance = AuthService._privateConstructor();

  /// 初始化Amplify Cognito认证插件
  Future<void> initAmplify() async {
    try {
      // 替换为你已获取的Cognito配置参数
      const authConfig = {
        'Plugins': {
          'awsCognitoAuthPlugin': {
            'Auth': {
              'region': '你的Cognito服务所属区域',
              'userPoolId': '你的Cognito用户池ID',
              'userPoolWebClientId': '你的Cognito应用客户端ID',
              'mandatorySignIn': true
            }
          }
        }
      };

      await Amplify.addPlugin(AmplifyAuthCognito());
      await Amplify.configure(authConfig);
    } on AmplifyException catch (e) {
      throw 'SDK初始化失败: ${e.message}';
    }
  }

  /// 触发OTP发送:用户输入已在Cognito中关联的手机号/邮箱后调用
  /// 注意:手机号需符合E.164格式,例如+86138XXXX1234
  Future<void> triggerOtpSend(String userContact) async {
    try {
      final signInResult = await Amplify.Auth.signIn(
        username: userContact.trim(),
      );
      // 校验认证流程步骤,确认Cognito已触发OTP发送
      if (signInResult.nextStep.signInStep == AuthStepType.confirmSignInWithOtpCode) {
        // 此时Cognito已将6位OTP码发送到用户填写的联系方式上
        return;
      }
      throw '当前账号未开通OTP登录权限,OTP发送失败';
    } on AuthException catch (e) {
      throw 'OTP发送异常: ${e.message}';
    }
  }

  /// 提交OTP完成登录认证
  Future<void> verifyOtpAndLogin(String otpCode) async {
    try {
      final confirmResult = await Amplify.Auth.confirmSignIn(
        confirmationCode: otpCode.trim(),
      );
      if (confirmResult.isSignedIn) {
        // 登录成功,可获取当前用户信息跳转应用主页
        return;
      }
      throw 'OTP验证未完成,请检查输入的验证码';
    } on AuthException catch (e) {
      // 覆盖OTP过期、输入错误、格式不匹配等常见异常
      throw 'OTP验证失败: ${e.message}';
    }
  }

  /// 退出登录
  Future<void> signOut() async {
    try {
      await Amplify.Auth.signOut();
    } on AuthException catch (e) {
      throw '退出登录失败: ${e.message}';
    }
  }
}

页面层对接示例

在登录页面完成初始化与交互绑定,即可实现完整的无密码登录流程:

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

  @override
  State<OtpLoginPage> createState() => _OtpLoginPageState();
}

class _OtpLoginPageState extends State<OtpLoginPage> {
  final _contactInputController = TextEditingController();
  final _otpInputController = TextEditingController();
  bool _hasOtpSent = false;
  String? _errorTip;

  @override
  void initState() {
    super.initState();
    // 页面加载时初始化Amplify认证能力
    AuthService.instance.initAmplify();
  }

  // 发送OTP按钮触发逻辑
  Future<void> _handleSendOtp() async {
    try {
      setState(() => _errorTip = null);
      await AuthService.instance.triggerOtpSend(_contactInputController.text);
      setState(() => _hasOtpSent = true);
    } catch (e) {
      setState(() => _errorTip = e.toString());
    }
  }

  // OTP验证登录触发逻辑
  Future<void> _handleConfirmLogin() async {
    try {
      setState(() => _errorTip = null);
      await AuthService.instance.verifyOtpAndLogin(_otpInputController.text);
      // 登录成功后跳转应用主页逻辑
    } catch (e) {
      setState(() => _errorTip = e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('OTP无密码登录')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _contactInputController,
              decoration: const InputDecoration(
                labelText: '已注册手机号/邮箱',
                hintText: '手机号需为E.164格式,如+86138XXXX1234',
              ),
            ),
            if (_hasOtpSent) ...[
              const SizedBox(height: 16),
              TextField(
                controller: _otpInputController,
                decoration: const InputDecoration(
                  labelText: '6位OTP验证码',
                ),
                keyboardType: TextInputType.number,
                maxLength: 6,
              ),
            ],
            if (_errorTip != null) ...[
              const SizedBox(height: 12),
              Text(
                _errorTip!,
                style: const TextStyle(color: Colors.red),
              ),
            ],
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _hasOtpSent ? _handleConfirmLogin : _handleSendOtp,
              child: Text(_hasOtpSent ? '验证并登录' : '发送OTP验证码'),
            )
          ],
        ),
      ),
    );
  }
}

实现逻辑说明

  • 整个流程全程不需要用户输入固定密码,完全通过OTP校验完成身份认证
  • 自动对接Cognito的认证挑战机制,无需手动解析自定义挑战的请求格式
  • 覆盖SDK初始化、OTP发送、OTP校验、登录状态判定、异常捕获、退出登录全场景
  • 全部依赖官方维护的Amplify插件,无第三方包兼容性问题,可直接在生产环境运行

内容的提问来源于stack exchange,提问作者Praharsh Bhatt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 22:06:04