AWS Cognito无法验证客户端的秘密哈希值

时间:2017-04-27 13:33:23

标签: javascript amazon-web-services aws-sdk amazon-cognito

当我尝试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上,客户端密钥已被禁用

enter image description here

2 个答案:

答案 0 :(得分:12)

适用于JavaScript的Amazon Cognito Identity SDK不支持具有客户端密钥的应用。这在SDK documentation

中说明
  

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

看起来您将不得不重新配置您的应用。

答案 1 :(得分:0)

解决方案是将 secret_hash 与 adminAuthInitiate 请求一起传递。要计算秘密哈希,您可以使用以下方法:

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();