尝试在 Flutter 中使用 AWS Cognito 在用户注册期间验证确认码

问题描述 投票:0回答:1

我正在尝试在 Flutter 中使用 AWS Cognito 验证注册应用程序的用户的确认代码。我收到错误请求,状态 400 错误

NotAuthorizedException
(完整错误显示在底部)。我通过 AWS 仪表板使用 AWS Cognito 设置了用户池和应用程序客户端。我在 Flutter 应用程序中使用
amazon_cognito_identity_dart_2
库。

amazon_cognito_identity_dart_2: ^3.6.5

下面是代码。

confirmSignUp
方法是我陷入困境的地方。如果计划运行代码,请插入用户池 ID、客户端 ID 和客户端密钥:

import 'package:amazon_cognito_identity_dart_2/cognito.dart';
import 'dart:convert';

class CognitoService {
  final List<AttributeArg> userAttributes = [];
  final CognitoUserPool userPool = new CognitoUserPool(
    'UserPoolID', 'Client Id',   clientSecret: 'Client Secret');

  // Working
  Future<bool> signUp(String email, String password) async {
    try {
      await userPool.signUp(email, password);
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  // Below is causing the error
  Future<bool> confirmSignUp(String email, String confirmationCode) async {
    try {
      final cognitoUser = CognitoUser(email, userPool);
      return await cognitoUser.confirmRegistration(confirmationCode);
    } catch (e) {
      print(e);
      return false;
    }
  }
}

错误指出:

browser_client.dart:101
POST https://cognito-idp.us-east-1.amazonaws.com/ 400 (Bad Request)

随后:

CognitoClientException{statusCode: 400, code: NotAuthorizedException, name: NotAuthorizedException, message: Client 4je8c3ohh0nnqogebbc2e8c8mt is configured with secret but SECRET_HASH was not received}

我输入了确认号码,但用户从未获得授权。

如有任何有关此事的建议,我们将不胜感激。

flutter amazon-cognito
1个回答
0
投票

正如评论部分所解释的,你可以尝试实现这个吗:

import 'package:amazon_cognito_identity_dart_2/cognito.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';

class CognitoService {
  final CognitoUserPool userPool = CognitoUserPool(
    'UserPoolID',
    'ClientId',
    clientSecret: 'ClientSecret',
  );

  String calculateSecretHash(String clientId, String clientSecret, String username) {
    final hmacSha256 = Hmac(sha256, utf8.encode(clientSecret)); // HMAC-SHA256
    final digest = hmacSha256.convert(utf8.encode(username + clientId));
    return base64Encode(digest.bytes);
  }

  // Working
  Future<bool> signUp(String email, String password) async {
    try {
      await userPool.signUp(email, password);
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  // Updated confirmSignUp method
  Future<bool> confirmSignUp(String email, String confirmationCode) async {
    try {
      final cognitoUser = CognitoUser(email, userPool);
      final secretHash = calculateSecretHash(userPool.getClientId(), userPool.getClientSecret(), email);
      return await cognitoUser.confirmRegistration(confirmationCode, secretHash: secretHash);
    } catch (e) {
      print(e);
      return false;
    }
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.