Aws Cognito:Java SDK(非Android)和ADMIN_NO_SRP_AUTH流的秘密哈希

时间:2017-02-06 18:49:29

标签: amazon-web-services amazon-cognito

我尝试使用我的java后端的用户名和密码在我的amazon cognito用户池中注册用户,但我总是收到错误:

Unable to verify secret hash for client

在文档中我没有找到任何关于如何在注册请求中传递clientSecret的信息,我不喜欢在没有clientSecret的情况下创建(后端)应用程序。

我的代码看起来像这样

identityProvider = AWSCognitoIdentityProviderClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion(Regions.EU_CENTRAL_1).build();

Map<String, String> authParameters = new HashMap<>();
authParameters.put("USERNAME", "username");
authParameters.put("PASSWORD", "password");
authParameters.put("SECRET_HASH", "secret copy and paste from the aws console"); // i read in a forum post, that this should work

AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest();
authRequest.withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH);
authRequest.setAuthParameters(authParameters);
authRequest.setClientId("clientId");
authRequest.setUserPoolId("userPoolId");

AdminInitiateAuthResult authResponse = identityProvider.adminInitiateAuth(authRequest);

由于 烫发

2 个答案:

答案 0 :(得分:1)

要注册用户,您应该使用SignUp API。秘密哈希可以在Java中计算如下:

public String calculateSecretHash(String userPoolclientId, String userPoolclientSecret, String userName) {
        if (userPoolclientSecret == null) {
            return null;
        }

        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 Encoding.encodeBase64(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException("Error while calculating ");
        }
    }

请您详细说明从后端创建用户的用例,而不是直接从客户端调用Amazon Cognito?

修改:我们更新了文档,其中包含有关如何compute the secret hash

的部分

答案 1 :(得分:0)

以下代码完美无缺:

    AdminInitiateAuthRequest adminInitiateAuthRequest = new AdminInitiateAuthRequest().withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH).withClientId("<ID of your client application>").withUserPoolId("<your user pool ID>")
            .addAuthParametersEntry("USERNAME", "<your user>").addAuthParametersEntry("PASSWORD", "<your password for the user>");
    AdminInitiateAuthResult adminInitiateAuth = identityProvider.adminInitiateAuth(adminInitiateAuthRequest);
    System.out.println(adminInitiateAuth.getAuthenticationResult().getIdToken());