AWS Cognito 客户端无法验证密钥哈希

8
当我尝试进行authenticateUser时,出现以下错误:Error: Unable to verify secret hash for client <CLIENT_ID_HERE>。我的代码如下:
import {
  Config,
  CognitoIdentityCredentials
} from "aws-sdk"
import {
  CognitoUserPool,
  CognitoUserAttribute,
  AuthenticationDetails,
  CognitoUser
} from "amazon-cognito-identity-js"

Config.region = "ap-northeast-2"

var userpool = new CognitoUserPool({
  UserPoolId: "ap-northeast-2_QosOiWMkd",
  ClientId: "1bd6s9mv98bo2lucen2vesbqls"
})

var userData = {
  Username: "jiewmeng@gmail.com",
  Pool: userpool
}

var authData = new AuthenticationDetails({
  Username: "jiewmeng@gmail.com",
  Password: "P@$$w0rd"
})

var cognitoUser = new CognitoUser(userData)
cognitoUser.authenticateUser(authData, {
  onSuccess: function (result) {
    console.log("authenticated with", result)
  },
  onFailure: function (err) {
    console.error(err)
  }
})

在AWS上,客户端密钥已经被禁用。

输入图像描述

2个回答

16

亚马逊 Cognito Identity SDK for JavaScript 不支持带有客户端秘钥的应用程序。这在 SDK 文档 中已经说明:

创建应用程序时,必须取消生成客户端秘钥框中的勾选,因为 JavaScript SDK 不支持拥有客户端秘钥的应用程序。

看起来您需要重新配置您的应用程序。


但是从我发布的图片中可以看到,客户端密钥已经被禁用了? - Jiew Meng
我发现你是正确的,奇怪的是,今天当我再次检查时,有一个客户端秘钥...不确定是否需要一段时间才能显示或其他什么... - Jiew Meng
请看这个答案:https://dev59.com/d1oU5IYBdhLWcg3wc2xW#66819267 - Utkarsh
哦,天啊...又开始了...谢谢! - Edward Casanova

0
解决方案是在adminAuthInitiate请求中传递secret_hash。要计算secret hash,您可以使用以下方法:
public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) {
final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
        SecretKeySpec signingKey = new SecretKeySpec(
                userPoolClientSecret.getBytes(StandardCharsets.UTF_8),
                HMAC_SHA256_ALGORITHM);
        try {
            Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
            mac.init(signingKey);
            mac.update(userName.getBytes(StandardCharsets.UTF_8));
            byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException("Error while calculating ");
        }
    }

如何通过 Secret_Hash
Map<String, String> authParams = new HashMap<>(2);
authParams.put("USERNAME", <username>);
authParams.put("PASSWORD", <password>);
                    authParams.put("SECRET_HASH", calculateSecretHash(cognitoClientId, cognitoClientSecret, <username>));
                    AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
                            .withClientId(userPool.getClientId()).withUserPoolId(userPool.getUserPoolId())
                            .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH).withAuthParameters(authParams);
                    AdminInitiateAuthResult result = cognito.adminInitiateAuth(authRequest);
                    auth = result.getAuthenticationResult();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接